Skip to main content

jmap_tasks_server/
backend.rs

1//! TasksBackend trait and supporting types for JMAP Tasks method handlers.
2//!
3//! Consumers implement [`TasksBackend`] for their storage system. The method
4//! handlers in sibling modules call into the backend through this trait.
5//!
6//! The read-side operations (`get_objects`, `get_state`, `get_changes`,
7//! `query_objects`, `query_changes`) are defined on the [`jmap_server::JmapBackend`]
8//! supertrait. Only write operations and type-specific operations are here.
9
10use jmap_server::{BackendSetError, JmapBackend, JmapObject, SetObject};
11use jmap_types::PatchObject;
12
13// ---------------------------------------------------------------------------
14// TasksBackend trait
15// ---------------------------------------------------------------------------
16
17/// Storage backend for JMAP Tasks method handlers (draft-ietf-jmap-tasks-06).
18///
19/// Implementors provide the actual data access; the method handler modules
20/// in this crate translate between JMAP wire protocol and backend calls.
21///
22/// Read-side operations (`get_objects`, `get_state`, `get_changes`,
23/// `query_objects`, `query_changes`) are defined on the [`JmapBackend`]
24/// supertrait. Only write operations and type introspection are here.
25///
26/// This trait is not object-safe by design (generic methods). Use
27/// `Arc<impl TasksBackend>` when sharing across tasks.
28pub trait TasksBackend: JmapBackend {
29    /// Create a new object (TaskList or Task).
30    ///
31    /// # Authorisation contract
32    ///
33    /// This method is the canonical enforcement point for caller authorisation
34    /// per workspace AGENTS.md "Caller identity (foundation seam)" and per-crate
35    /// AGENTS.md "Permission enforcement: backend canonical". Implementors MUST
36    /// verify that the principal identified by
37    /// [`JmapBackend::principal_id(caller)`](JmapBackend::principal_id) has write
38    /// access to the target account / TaskList / Task before performing the
39    /// mutation, and MUST return
40    /// [`BackendSetError::SetError`] carrying
41    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. Handlers in this crate do NO
42    /// permission checking; any handler-layer pre-check is defense-in-depth
43    /// only and the backend MUST re-verify atomically with the mutation. A
44    /// backend that trusts the handler is a bug. A backend whose
45    /// `principal_id` returns `None` permits every write (fail-open,
46    /// bd:JMAP-bghk) and CANNOT correctly implement TaskList ACLs or
47    /// per-user scoping.
48    ///
49    /// # Errors
50    ///
51    /// Reject a create that RFC 8620 §5.3 defines an error for with
52    /// [`BackendSetError::SetError`] carrying the matching
53    /// [`SetErrorType`](jmap_server::SetErrorType); the handler places it verbatim in `notCreated`.
54    /// For create these are `forbidden`, `overQuota`, `tooLarge`,
55    /// `rateLimit` and `invalidProperties`. An `invalidProperties` error
56    /// SHOULD name in `properties` "*all* the properties that were
57    /// invalid", for example `taskListId` when a Task names a TaskList that
58    /// does not exist.
59    ///
60    /// Return [`BackendSetError::Other`] only for unexpected storage
61    /// failures. The handler reports it as `serverFail` without the
62    /// error's `Display` text, which tells the client to retry; a
63    /// deterministic rejection returned as `Other` invites retries that
64    /// cannot succeed.
65    ///
66    /// The `/set` handlers in this crate reject an unknown `account_id`
67    /// with the method-level `accountNotFound` error before calling the
68    /// backend.
69    ///
70    /// # State and change log
71    ///
72    /// RFC 8620 §5.1 defines the state string over "*all* the data of
73    /// this type in the account": "If the data changes, this string MUST
74    /// change." Every successful `create_object`,
75    /// [`update_object`](Self::update_object) and
76    /// [`destroy_object`](Self::destroy_object) MUST advance
77    /// [`get_state`](JmapBackend::get_state) for `O` in `account_id` and
78    /// record the id as created, updated or destroyed so
79    /// [`get_changes`](JmapBackend::get_changes) reports it.
80    ///
81    /// The write, the state advance and the change record MUST be atomic
82    /// with respect to other callers: the reference `MemoryBackend` does
83    /// all three under one mutex acquisition, and a database backend uses
84    /// one transaction. A call that returns `Err` MUST leave the stored
85    /// data, the state and the change log unchanged.
86    fn create_object<O, F>(
87        &self,
88        caller: &Self::CallerCtx,
89        account_id: &jmap_types::Id,
90        create_id: &str,
91        build: F,
92    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
93    + Send
94    where
95        O: SetObject + Send + Sync,
96        F: FnOnce(&jmap_types::Id) -> O + Send;
97
98    /// Store `obj`, a record read from `from_account_id`, as a new record in
99    /// `to_account_id`, for `/copy` (RFC 8620 §5.4).
100    ///
101    /// Called by `Task/copy` after the handler fetched the Task from
102    /// `from_account_id` and applied the request's overrides, including any
103    /// `metadata` and `privateMetadata` it supplies
104    /// (draft-ietf-jmap-metadata-04 §3.4). `create` is the request's create
105    /// object for this copy (RFC 8620 §5.4). -04 §3.4 says its `metadata`
106    /// and `privateMetadata` follow "the same rules as a create in
107    /// Foo/set", so the backend validates them as
108    /// [`create_object`](Self::create_object) does (-04 §3.2 rules 1 to 4,
109    /// `maxDepth` only on these supplied values) and leaves the copied
110    /// values unvalidated ("Copied values are not revalidated against the
111    /// destination account"). Every other rule of
112    /// [`create_object`](Self::create_object) applies to the copy. The
113    /// backend assigns the new `id`, stores the record in `to_account_id`
114    /// and records the create in the state and change log as
115    /// [`create_object`](Self::create_object) does. Returns the new id and
116    /// the stored record.
117    ///
118    /// # Authorisation contract
119    ///
120    /// Implementors MUST verify caller read access to `obj` in
121    /// `from_account_id` and write access to `to_account_id` before storing the
122    /// copy, and MUST return [`BackendSetError::SetError`] with
123    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
124    /// the workspace-canonical rationale; the same rule applies here.
125    ///
126    /// # Errors
127    ///
128    /// As for [`create_object`](Self::create_object): a
129    /// [`BackendSetError::SetError`] is reported for that copy.
130    fn copy_object<O: SetObject + Send + Sync>(
131        &self,
132        caller: &Self::CallerCtx,
133        from_account_id: &jmap_types::Id,
134        to_account_id: &jmap_types::Id,
135        obj: O,
136        create: &serde_json::Value,
137    ) -> impl std::future::Future<Output = Result<(jmap_types::Id, O), BackendSetError<Self::Error>>>
138    + Send;
139
140    /// Apply a partial update (patch) to an existing object.
141    ///
142    /// Returns `Some(updated_object)` if the backend modified any properties
143    /// beyond what the client requested (RFC 8620 §5.3 server-set field echo),
144    /// or `None` if the patch was applied verbatim.
145    ///
146    /// # Authorisation contract
147    ///
148    /// Implementors MUST verify caller write-access to the target object before
149    /// applying the patch and MUST return [`BackendSetError::SetError`] with
150    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
151    /// the workspace-canonical rationale; the same rule applies here.
152    ///
153    /// # Patch format
154    ///
155    /// `patch` is an RFC 8620 §5.3 PatchObject, not an RFC 7396 JSON
156    /// Merge Patch: "The keys are a path in JSON Pointer format
157    /// \[RFC6901\], with an implicit leading "/"". So `{"a/b": null}`
158    /// removes member `b` of property `a`; it does not touch a top-level
159    /// property literally named `a/b`. A `null` value sets the
160    /// property's default if it has one, otherwise removes it. A pointer
161    /// into an array, a pointer whose parent does not exist, or two keys
162    /// where one pointer is a prefix of the other "MUST be rejected with
163    /// an "invalidPatch" error".
164    ///
165    /// Implementors SHOULD apply `patch` with
166    /// [`jmap_server::apply_patch_object`], which enforces these rules
167    /// all-or-nothing, and map any [`jmap_server::PatchPathError`] to
168    /// [`jmap_server::SetErrorType::InvalidPatch`], as the reference
169    /// `MemoryBackend` does.
170    ///
171    /// # Errors
172    ///
173    /// As for [`create_object`](Self::create_object), plus these RFC 8620
174    /// §5.3 rules for update:
175    ///
176    /// - "If an id given cannot be found, the update or destroy MUST be
177    ///   rejected with a "notFound" set error."
178    /// - A patch that breaks the rules under "Patch format" is
179    ///   `invalidPatch`.
180    /// - A patched record that is invalid is `invalidProperties`. That
181    ///   includes changing a server-set property, though "it is not an
182    ///   error to include a server-set property in an update as long as
183    ///   the value is identical to the current value on the server."
184    /// - A Task patch whose result has `isDraft: true` when the stored
185    ///   value is not `true` (false, or absent after a `null` patch) is
186    ///   `invalidProperties` naming `isDraft`: draft-tasks-06 §4 "This may
187    ///   only be set to true upon creation." The `Task/set` handler does
188    ///   not pre-check this; the backend is the only enforcement point, in
189    ///   the same critical section that applies the patch.
190    ///
191    /// # Atomicity
192    ///
193    /// RFC 8620 §5.3: the server "MUST NOT only commit part of an update
194    /// to a single record". Apply the whole patch and validate the result
195    /// before writing it, so that on any error the stored record is
196    /// unchanged. State and change log follow
197    /// [`create_object`](Self::create_object) ("State and change log"); an
198    /// `Ok(None)` return still advances the state.
199    fn update_object<O: SetObject + Send + Sync>(
200        &self,
201        caller: &Self::CallerCtx,
202        account_id: &jmap_types::Id,
203        id: &jmap_types::Id,
204        patch: O::Patch,
205    ) -> impl std::future::Future<Output = Result<Option<O>, BackendSetError<Self::Error>>> + Send;
206
207    /// Destroy an object by id.
208    ///
209    /// # Authorisation contract
210    ///
211    /// Implementors MUST verify caller write-access to the target object before
212    /// destroying it and MUST return [`BackendSetError::SetError`] with
213    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. See [`Self::create_object`] for
214    /// the workspace-canonical rationale; the same rule applies here.
215    ///
216    /// # Errors
217    ///
218    /// As for [`create_object`](Self::create_object), plus these RFC 8620
219    /// §5.3 rules for destroy: an unknown id, including one already
220    /// destroyed, is `notFound`, and a destroy that "would violate an ACL
221    /// or other permissions policy" is `forbidden`.
222    ///
223    /// # Cascades
224    ///
225    /// The handlers perform the cross-record effects the client chooses,
226    /// through explicit backend calls, and the backend does not repeat
227    /// them. `TaskList/set` `onDestroyRemoveTasks` does not yet destroy
228    /// the list's Tasks (bd:JMAP-ji1v).
229    ///
230    /// If the backend itself changes another record because of the
231    /// destroy, it MUST advance that record type's state and record the
232    /// change in the same atomic step, so `/changes` on that type sees it.
233    /// State and change log for `O` follow
234    /// [`create_object`](Self::create_object) ("State and change log").
235    fn destroy_object<O: SetObject + Send + Sync>(
236        &self,
237        caller: &Self::CallerCtx,
238        account_id: &jmap_types::Id,
239        id: &jmap_types::Id,
240    ) -> impl std::future::Future<Output = Result<(), BackendSetError<Self::Error>>> + Send;
241
242    /// Returns `true` if this backend supports JMAP object type `O` for
243    /// `account_id`, as seen by `caller`.
244    ///
245    /// # Per-account semantics
246    ///
247    /// Capabilities are per account (RFC 8620 §1.6.2, §2
248    /// `accountCapabilities`), so the answer may vary with `caller` and
249    /// `account_id`. Backends that support every type in this trait for
250    /// every account can ignore both arguments and return `true`.
251    fn supports_type<O: JmapObject>(
252        &self,
253        caller: &Self::CallerCtx,
254        account_id: &jmap_types::Id,
255    ) -> bool;
256
257    /// Returns true if the given task list contains at least one task.
258    ///
259    /// Called by `TaskList/set` destroy handler when `onDestroyRemoveTasks`
260    /// is false: if this returns `Ok(true)`, the destroy is rejected with
261    /// `taskListHasTask` (draft-ietf-jmap-tasks-06 §3.4).
262    ///
263    /// # Three-way result
264    ///
265    /// The return type is `Result<bool, Self::Error>` to distinguish
266    /// three states that callers actually need to tell apart
267    /// (mirrors [`CalendarsBackend::calendar_has_events`]):
268    ///
269    /// - `Ok(true)` — the task list is definitely non-empty. The
270    ///   handler rejects the destroy with `taskListHasTask`.
271    /// - `Ok(false)` — the task list is definitely empty. The handler
272    ///   forwards to `destroy_object`.
273    /// - `Err(_)` — connectivity/transient failure. The handler maps
274    ///   this to `serverFail` so the client knows to retry. Returning
275    ///   `Ok(false)` for a transient backend failure is a bug: the
276    ///   destroy proceeds and any tasks that DID exist become silently
277    ///   orphaned.
278    ///
279    /// [`CalendarsBackend::calendar_has_events`]: https://docs.rs/jmap-calendars-server/latest/jmap_calendars_server/trait.CalendarsBackend.html#tymethod.calendar_has_events
280    ///
281    /// # Authorisation contract
282    ///
283    /// This is a read-side probe that informs a destroy decision the caller is
284    /// already authorised to attempt; implementors MAY assume the caller has at
285    /// least read access to the target TaskList (the surrounding `/set` flow
286    /// re-validates write access in [`Self::destroy_object`]). Backends that
287    /// scope task visibility per-principal MUST filter by the caller's effective
288    /// access — a counter that includes tasks the caller cannot see leaks
289    /// existence information.
290    fn task_list_has_tasks(
291        &self,
292        caller: &Self::CallerCtx,
293        account_id: &jmap_types::Id,
294        task_list_id: &jmap_types::Id,
295    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;
296
297    /// Apply a patch that contains only per-user Task properties
298    /// (draft-tasks-06 §4.5.1 — `keywords`, `color`, `freeBusyStatus`,
299    /// `useDefaultAlerts`, `alerts`).
300    ///
301    /// The handler routes here when every patch key's leading segment
302    /// satisfies [`jmap_tasks_types::is_per_user_task_property`]; that
303    /// classification is fixed by the spec and is not a backend hook.
304    ///
305    /// When only per-user properties are patched, the shared `updated`
306    /// timestamp MUST NOT change (§4.5.1 (per-user updated paragraph)).
307    /// There is no default: delegating to [`Self::update_object`] is correct
308    /// only for a single-user backend whose `update_object` leaves `updated`
309    /// alone. A backend serving multiple users stores the patch in a
310    /// user-scoped path.
311    ///
312    /// # Authorisation contract
313    ///
314    /// Implementors MUST verify that the caller may modify per-user properties
315    /// on the target Task and MUST return [`BackendSetError::SetError`] with
316    /// [`SetErrorType::Forbidden`](jmap_server::SetErrorType::Forbidden) otherwise. That is the TaskList's
317    /// `mayUpdatePrivate` right, which draft-ietf-jmap-tasks-06 §3 defines as:
318    /// "The user may modify the following properties on all tasks in the task
319    /// list, even if they would not otherwise have permission to modify that
320    /// task." The write-access rule of [`Self::update_object`] does NOT apply
321    /// here. See [`Self::create_object`] for the workspace-canonical rationale
322    /// on backend-as-enforcement-point.
323    fn update_task_per_user(
324        &self,
325        caller: &Self::CallerCtx,
326        account_id: &jmap_types::Id,
327        id: &jmap_types::Id,
328        patch: PatchObject,
329    ) -> impl std::future::Future<
330        Output = Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>>,
331    > + Send;
332
333    /// Compute `utcStart` and `utcDue` for a [`Task`](jmap_tasks_types::Task) by converting the task's
334    /// `start`/`due` local-time fields and time zone into UTC (draft-tasks-06 §4,
335    /// utcStart/utcDue paragraphs).
336    ///
337    /// Returns `(utc_start, utc_due)` as [`UTCDate`](jmap_types::UTCDate) values,
338    /// or `None` for each if the corresponding field is absent or the time zone
339    /// is unknown.
340    ///
341    /// The default implementation returns `(None, None)` — backends that do not
342    /// support time-zone conversion can accept this behaviour and the caller will
343    /// omit both fields.  Backends with full tz support should override this.
344    ///
345    /// # Parameters
346    /// - `caller` — the caller context. The default implementation ignores it,
347    ///   but backends MAY use [`JmapBackend::principal_id`] to resolve the
348    ///   caller's preferred default time zone when `tz_hint` is `None`.
349    /// - `account_id` — the target account. The default implementation ignores
350    ///   it, but backends MAY use it to look up an account-scoped tz database
351    ///   or per-account default time zone.
352    /// - `task` — the task whose `start` and `due` fields are to be converted.
353    /// - `tz_hint` — an optional IANA time-zone override; if `None`, the task's
354    ///   own `time_zone` field (if any) is used.
355    ///
356    /// Naming and signature mirror the canonical
357    /// [`CalendarsBackend::compute_utc_times`](https://docs.rs/jmap-calendars-server/latest/jmap_calendars_server/trait.CalendarsBackend.html#method.compute_utc_times)
358    /// (bd:JMAP-ops7.25).
359    ///
360    /// [`JmapBackend::principal_id`]: jmap_server::JmapBackend::principal_id
361    fn compute_utc_times(
362        &self,
363        _caller: &Self::CallerCtx,
364        _account_id: &jmap_types::Id,
365        _task: &jmap_tasks_types::Task,
366        _tz_hint: Option<&str>,
367    ) -> impl std::future::Future<
368        Output = (Option<jmap_types::UTCDate>, Option<jmap_types::UTCDate>),
369    > + Send {
370        // Default: no UTC conversion capability; callers omit utcStart/utcDue.
371        async { (None, None) }
372    }
373}