Skip to main content

jmap_tasks_server/
task_notification.rs

1//! TaskNotification/* method handlers (draft-tasks-06 §5).
2//!
3//! TaskNotifications are server-created immutable records. Clients may only
4//! query and destroy them. Any attempt to create or update a TaskNotification
5//! via `/set` MUST be rejected with `forbidden` at the handler layer — the
6//! backend never sees create or update calls for this type.
7//!
8//! # Wire-shape contract
9//!
10//! Every `handle_*` function in this module conforms to the canonical JMAP
11//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
12//! Object whose fields match the corresponding RFC 8620 §5 method shape
13//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3,
14//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
15//! arguments defined by draft-tasks-06 §5. The returned `Value` is the
16//! corresponding method-response object per the same section refs.
17//!
18//! The returned `HandlerOutput::extra_invocations` carries any invocations
19//! that this handler injected into the request stream (RFC 8620 §6.3);
20//! for the handlers in this module the vector is **always empty**.
21//!
22//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
23//! §3.6.2 and §5):
24//!
25//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
26//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
27//!   `maxObjectsInSet`;
28//! - `/set`: `stateMismatch`;
29//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
30//! - `/queryChanges`: `tooManyChanges`;
31//! - `/query`, `/queryChanges`: `unsupportedFilter`;
32//! - `/query`: `unsupportedSort`, `anchorNotFound`.
33//!
34//! Per-target failures inside `/set` surface in the `notDestroyed` map within
35//! `Ok((Value, ...))`, not as `Err`.
36
37use jmap_tasks_types::{TaskNotification, TaskNotificationComparator};
38use jmap_types::JmapError;
39use serde_json::Value;
40
41use crate::TasksBackend;
42use crate::helpers::{
43    SetAccumulators, enforce_max_objects_in_set, extract_account_id, finalize_set_response,
44    reject_unsupported_sort,
45};
46use jmap_server::{HandlerOutput, backend_set_error_value, server_fail_from_backend};
47use jmap_server::{SetError, SetErrorType};
48
49// ---------------------------------------------------------------------------
50// TaskNotification/get
51// ---------------------------------------------------------------------------
52
53/// Handle a `TaskNotification/get` method call (draft-tasks-06 §5.2).
54///
55/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
56/// `ids`, optional `properties`); the returned `Value` is the §5.1
57/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
58///
59/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
60pub async fn handle_task_notification_get<B: TasksBackend>(
61    backend: &B,
62    caller: &B::CallerCtx,
63    args: Value,
64) -> Result<HandlerOutput, JmapError> {
65    jmap_server::handle_get::<TaskNotification, B>(backend, caller, args).await
66}
67
68// ---------------------------------------------------------------------------
69// TaskNotification/changes
70// ---------------------------------------------------------------------------
71
72/// Handle a `TaskNotification/changes` method call (draft-tasks-06 §5.3).
73///
74/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
75/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
76/// `/changes` response shape (`accountId`, `oldState`, `newState`,
77/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
78///
79/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
80pub async fn handle_task_notification_changes<B: TasksBackend>(
81    backend: &B,
82    caller: &B::CallerCtx,
83    args: Value,
84) -> Result<HandlerOutput, JmapError> {
85    jmap_server::handle_changes::<TaskNotification, B>(backend, caller, args, &[]).await
86}
87
88// ---------------------------------------------------------------------------
89// TaskNotification/set
90// ---------------------------------------------------------------------------
91
92/// Handle a `TaskNotification/set` method call (draft-tasks-06 §5.4).
93///
94/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
95/// `ifInState`, optional `create` / `update` / `destroy` maps); the
96/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
97/// `oldState`, `newState`, plus the per-operation result maps).
98///
99/// **Destroy-only enforcement**: draft-tasks-06 §5.4 states that only
100/// `destroy` is supported. Any entries in the `create` or `update` maps
101/// receive an immediate `forbidden` SetError without touching the backend.
102/// The `destroy` list is forwarded to the backend normally.
103///
104/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
105pub async fn handle_task_notification_set<B: TasksBackend>(
106    backend: &B,
107    caller: &B::CallerCtx,
108    args: Value,
109) -> Result<HandlerOutput, JmapError> {
110    let (account_id, mut args) = extract_account_id(args)?;
111
112    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
113    // error). Without this, a /set against an unknown accountId would silently
114    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
115    if !backend
116        .account_exists(caller, &account_id)
117        .await
118        .map_err(|e| server_fail_from_backend(&e))?
119    {
120        return Err(JmapError::account_not_found());
121    }
122
123    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
124    // unbounded /set batches before touching the storage layer.
125    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
126
127    let old_state = backend
128        .get_state::<TaskNotification>(caller, &account_id)
129        .await
130        .map_err(|e| server_fail_from_backend(&e))?;
131
132    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
133        && if_in_state != old_state.as_ref()
134    {
135        return Err(JmapError::state_mismatch());
136    }
137
138    let created = serde_json::Map::new();
139    let mut not_created = serde_json::Map::new();
140    let updated = serde_json::Map::new();
141    let mut not_updated = serde_json::Map::new();
142    let mut destroyed_list: Vec<Value> = Vec::new();
143    let mut not_destroyed = serde_json::Map::new();
144    let mut mutated = false;
145
146    // -----------------------------------------------------------------------
147    // create — forbidden: TaskNotification is server-created only
148    // -----------------------------------------------------------------------
149    if let Some(create_map) = args.get("create").and_then(|v| v.as_object()) {
150        for create_id in create_map.keys() {
151            not_created.insert(
152                create_id.clone(),
153                serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
154            );
155        }
156    }
157
158    // -----------------------------------------------------------------------
159    // update — forbidden: TaskNotification is immutable
160    // -----------------------------------------------------------------------
161    if let Some(update_map) = args.get("update").and_then(|v| v.as_object()) {
162        for id_str in update_map.keys() {
163            not_updated.insert(
164                id_str.clone(),
165                serde_json::Value::from(&SetError::new(SetErrorType::Forbidden)),
166            );
167        }
168    }
169
170    // -----------------------------------------------------------------------
171    // destroy — the only permitted operation (draft-tasks-06 §5.4)
172    // -----------------------------------------------------------------------
173    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
174        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
175        // Two-pass validation is intentional: this up-front loop fails the whole
176        // request loudly; the `None => continue` arm in the inner match below
177        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
178        // delete this pre-check on the reasoning that the inner match handles
179        // non-string elements — silent-skip is the wrong behaviour per the
180        // workspace "silent-drop is a data-integrity bug class" rule
181        // (JMAP-wlip.1).
182        let id_strs: Vec<&str> = destroy_arr
183            .iter()
184            .map(|v| {
185                v.as_str().ok_or_else(|| {
186                    JmapError::invalid_arguments(format!(
187                        "destroy: every element must be a string Id; got {}",
188                        jmap_server::json_type_name(v)
189                    ))
190                })
191            })
192            .collect::<Result<_, _>>()?;
193        for id_str in id_strs {
194            let id_str = id_str.to_owned();
195            let id = match jmap_server::parse_wire_id(&id_str, "id") {
196                Ok(id) => id,
197                Err(err) => {
198                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
199                    continue;
200                }
201            };
202
203            match backend
204                .destroy_object::<TaskNotification>(caller, &account_id, &id)
205                .await
206            {
207                Ok(()) => {
208                    mutated = true;
209                    destroyed_list.push(Value::String(id_str));
210                }
211                Err(e) => {
212                    not_destroyed.insert(id_str, backend_set_error_value(e));
213                }
214            }
215        }
216    }
217
218    finalize_set_response::<B, TaskNotification>(
219        backend,
220        caller,
221        &account_id,
222        old_state,
223        mutated,
224        SetAccumulators {
225            created,
226            updated,
227            destroyed: destroyed_list,
228            not_created,
229            not_updated,
230            not_destroyed,
231        },
232    )
233    .await
234}
235
236// ---------------------------------------------------------------------------
237// TaskNotification/query
238// ---------------------------------------------------------------------------
239
240/// Handle a `TaskNotification/query` method call (draft-tasks-06 §5.5).
241///
242/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
243/// optional `filter`, optional `sort`, optional `position`, optional
244/// `anchor`, optional `anchorOffset`, optional `limit`, optional
245/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
246/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
247/// `position`, `ids`, optional `total`).
248///
249/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
250pub async fn handle_task_notification_query<B: TasksBackend>(
251    backend: &B,
252    caller: &B::CallerCtx,
253    args: Value,
254) -> Result<HandlerOutput, JmapError> {
255    reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
256    jmap_server::handle_query::<TaskNotification, B>(backend, caller, args).await
257}
258
259// ---------------------------------------------------------------------------
260// TaskNotification/queryChanges
261// ---------------------------------------------------------------------------
262
263/// Handle a `TaskNotification/queryChanges` method call (draft-tasks-06 §5.6).
264///
265/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
266/// optional `filter`, optional `sort`, `sinceQueryState`, optional
267/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
268/// returned `Value` is the §5.6 `/queryChanges` response shape
269/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
270/// `removed`, `added`).
271///
272/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
273pub async fn handle_task_notification_query_changes<B: TasksBackend>(
274    backend: &B,
275    caller: &B::CallerCtx,
276    args: Value,
277) -> Result<HandlerOutput, JmapError> {
278    reject_unsupported_sort::<TaskNotificationComparator>(args.get("sort"))?;
279    jmap_server::handle_query_changes::<TaskNotification, B>(backend, caller, args).await
280}
281
282// ---------------------------------------------------------------------------
283// Tests
284// ---------------------------------------------------------------------------
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use serde_json::json;
290
291    use crate::test_support::MockBackend;
292
293    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
294    /// valid, but includes a property the server does not support sorting
295    /// on". draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
296    /// supported for sorting." and lists no other; `taskId` is not among them.
297    #[tokio::test]
298    async fn query_unlisted_sort_property_returns_unsupported_sort() {
299        let backend = MockBackend::new_with_account("acc1");
300        let args = json!({ "accountId": "acc1", "sort": [{ "property": "taskId" }] });
301        let err = handle_task_notification_query(&backend, &(), args)
302            .await
303            .expect_err("unlisted sort property must be rejected");
304        assert_eq!(err.error_type.to_string(), "unsupportedSort");
305    }
306
307    /// Oracle: as above; `TaskNotification/queryChanges` carries the same `sort`
308    /// (RFC 8620 §5.6).
309    #[tokio::test]
310    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
311        let backend = MockBackend::new_with_account("acc1");
312        let args = json!({
313            "accountId": "acc1",
314            "sinceQueryState": "0",
315            "sort": [{ "property": "created" }, { "property": "taskId" }]
316        });
317        let err = handle_task_notification_query_changes(&backend, &(), args)
318            .await
319            .expect_err("unlisted sort property must be rejected");
320        assert_eq!(err.error_type.to_string(), "unsupportedSort");
321    }
322
323    /// Oracle: draft-ietf-jmap-tasks-06 §5.5.2: "The \"created\" property MUST be
324    /// supported for sorting." and lists no other, so a `created` sort is accepted.
325    #[tokio::test]
326    async fn query_listed_sort_property_is_accepted() {
327        let backend = MockBackend::new_with_account("acc1");
328        let args = json!({ "accountId": "acc1", "sort": [{ "property": "created" }] });
329        handle_task_notification_query(&backend, &(), args)
330            .await
331            .expect("listed sort property must not be rejected");
332    }
333
334    /// Oracle: TaskNotification/set create entries must produce `forbidden` in notCreated.
335    /// No backend call is made for create (pure handler-layer enforcement).
336    #[tokio::test]
337    async fn set_create_returns_forbidden_not_created() {
338        let backend = MockBackend::new_with_account("acc1");
339        let args = json!({
340            "accountId": "acc1",
341            "create": {
342                "c1": {
343                    "id": "ignored",
344                    "created": "2024-01-01T00:00:00Z",
345                    "changedBy": { "@type": "Person", "name": "Alice" },
346                    "type": "created",
347                    "taskId": "t1"
348                }
349            }
350        });
351        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
352            .await
353            .expect("must not return top-level error");
354
355        let not_created = &resp["notCreated"];
356        assert!(
357            not_created.is_object(),
358            "notCreated must be present for create attempts: {resp}"
359        );
360        assert_eq!(
361            not_created["c1"]["type"], "forbidden",
362            "c1 create must be forbidden: {resp}"
363        );
364        assert!(
365            resp["created"].is_null(),
366            "created must be null when all creates are forbidden: {resp}"
367        );
368    }
369
370    /// Oracle: TaskNotification/set update entries must produce `forbidden` in notUpdated.
371    #[tokio::test]
372    async fn set_update_returns_forbidden_not_updated() {
373        let backend = MockBackend::new_with_account("acc1");
374        let args = json!({
375            "accountId": "acc1",
376            "update": {
377                "notif1": { "comment": "new comment" }
378            }
379        });
380        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
381            .await
382            .expect("must not return top-level error");
383
384        let not_updated = &resp["notUpdated"];
385        assert!(
386            not_updated.is_object(),
387            "notUpdated must be present for update attempts: {resp}"
388        );
389        assert_eq!(not_updated["notif1"]["type"], "forbidden");
390    }
391
392    /// Oracle: destroy of a non-existent notification → notFound in notDestroyed.
393    #[tokio::test]
394    async fn set_destroy_nonexistent_returns_not_found() {
395        let backend = MockBackend::new_with_account("acc1");
396        let args = json!({
397            "accountId": "acc1",
398            "destroy": ["doesnotexist"]
399        });
400        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
401            .await
402            .expect("must not return top-level error");
403
404        let not_destroyed = &resp["notDestroyed"];
405        assert!(
406            not_destroyed.is_object(),
407            "notDestroyed must be present: {resp}"
408        );
409        assert_eq!(
410            not_destroyed["doesnotexist"]["type"], "notFound",
411            "missing id must produce notFound: {resp}"
412        );
413    }
414
415    /// Oracle: destroy of existing notification → appears in destroyed list.
416    #[tokio::test]
417    async fn set_destroy_existing_notification_succeeds() {
418        let mut backend = MockBackend::new_with_account("acc1");
419        backend.add_notification("acc1", "notif1");
420
421        let args = json!({
422            "accountId": "acc1",
423            "destroy": ["notif1"]
424        });
425        let HandlerOutput { primary: resp, .. } = handle_task_notification_set(&backend, &(), args)
426            .await
427            .expect("must not return top-level error");
428
429        let destroyed = resp["destroyed"]
430            .as_array()
431            .expect("destroyed must be array");
432        assert_eq!(destroyed.len(), 1);
433        assert_eq!(destroyed[0], "notif1");
434    }
435}