Skip to main content

jmap_mail_client/methods/
identity.rs

1//! JMAP Mail — Identity/* method implementations on SessionClient.
2//!
3//! Each method follows the standard five-step pattern:
4//!   1. Validate arguments (defence-in-depth empty-state guards).
5//!   2. Call `self.session_parts()?` → `(api_url, account_id)`.
6//!   3. Build args JSON with `serde_json::json!({…})`.
7//!   4. Call `build_request(method_name, args, USING_SUBMISSION)`.
8//!   5. Call `self.call_internal(api_url, &req).await?`.
9//!   6. Call `jmap_base_client::extract_response(&resp, CALL_ID)?`.
10
11use std::collections::HashMap;
12
13use jmap_types::{Id, PatchObject, State};
14
15use super::{ChangesResponse, GetResponse, SetResponse};
16
17impl super::SessionClient {
18    /// Fetch Identity objects by IDs (RFC 8621 §6.1 — Identity/get).
19    ///
20    /// If `ids` is `None`, the server returns all Identities for the account,
21    /// SUBJECT TO the server's `maxObjectsInGet` cap (RFC 8620 §5.1).
22    /// For production use, scope the result set via the corresponding
23    /// /query method first and pass explicit ids here to avoid
24    /// `requestTooLarge` errors when the account holds more objects
25    /// than the cap.
26    /// Pass `properties: None` to return all fields.
27    ///
28    /// # Errors
29    ///
30    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
31    ///   if the bound session has no primary account for
32    ///   `urn:ietf:params:jmap:mail`. (Identity/* uses the
33    ///   `urn:ietf:params:jmap:submission` capability for its `using`
34    ///   array but is keyed on the mail primary account.)
35    /// - Any transport / protocol variant returned by
36    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call):
37    ///   [`Http`](jmap_base_client::ClientError::Http),
38    ///   [`Parse`](jmap_base_client::ClientError::Parse),
39    ///   [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
40    ///   [`MethodError`](jmap_base_client::ClientError::MethodError)
41    ///   (wraps RFC 8620 §3.6.2 method-level errors such as
42    ///   `accountNotFound`, `invalidArguments`, `serverFail`),
43    ///   [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
44    ///   [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
45    ///   or
46    ///   [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
47    pub async fn identity_get(
48        &self,
49        ids: Option<&[Id]>,
50        properties: Option<&[&str]>,
51    ) -> Result<GetResponse<jmap_mail_types::Identity>, jmap_base_client::ClientError> {
52        let (api_url, account_id) = self.session_parts()?;
53        // Omit `ids` / `properties` when None — see the matching comment on
54        // `email_get` for the rationale (consistent with set/changes/query).
55        let mut args = serde_json::json!({ "accountId": account_id });
56        if let Some(id_slice) = ids {
57            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
58        }
59        if let Some(props) = properties {
60            args["properties"] =
61                serde_json::to_value(props).expect("&[&str] Serialize is infallible");
62        }
63        let req = super::build_request("Identity/get", args, super::USING_SUBMISSION);
64        let resp = self.call_internal(api_url, &req).await?;
65        jmap_base_client::extract_response(&resp, super::CALL_ID)
66    }
67
68    /// Fetch changes to Identity objects since `since_state` (RFC 8621 §6.2 — Identity/changes).
69    ///
70    /// `max_changes` follows the same RFC 8620 §5.2 magic-value semantics
71    /// as [`SessionClient::email_changes`](crate::methods::SessionClient::email_changes):
72    /// `None` lets the server apply its default cap, `Some(0)` means
73    /// "no client limit", `Some(n>0)` requests at most `n` entries.
74    ///
75    /// # Errors
76    ///
77    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
78    ///   if `since_state` is the empty string (defence-in-depth —
79    ///   `State` constructed via [`State::from`](jmap_types::State::from)
80    ///   accepts empty strings, but an empty `sinceState` is never
81    ///   useful and would otherwise generate a wasted round-trip).
82    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
83    ///   if the bound session has no primary account for
84    ///   `urn:ietf:params:jmap:mail`.
85    /// - Any transport / protocol variant returned by
86    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
87    ///   the matching error list on [`Self::identity_get`].
88    pub async fn identity_changes(
89        &self,
90        since_state: &State,
91        max_changes: Option<u64>,
92    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
93        // Defence-in-depth: see `thread_changes`.
94        if since_state.as_ref().is_empty() {
95            return Err(jmap_base_client::ClientError::InvalidArgument(
96                "identity_changes: since_state may not be empty".into(),
97            ));
98        }
99        let (api_url, account_id) = self.session_parts()?;
100        let mut args = serde_json::json!({
101            "accountId": account_id,
102            "sinceState": since_state,
103        });
104        if let Some(mc) = max_changes {
105            args["maxChanges"] = mc.into();
106        }
107        let req = super::build_request("Identity/changes", args, super::USING_SUBMISSION);
108        let resp = self.call_internal(api_url, &req).await?;
109        jmap_base_client::extract_response(&resp, super::CALL_ID)
110    }
111
112    /// Create, update, or destroy Identity objects (RFC 8621 §6.3 — Identity/set).
113    ///
114    /// Pass `create`, `update`, and/or `destroy` as needed. Pass `None` to omit.
115    ///
116    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
117    /// format is unchanged from a plain JSON object because [`PatchObject`]
118    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
119    /// key + null-leaf removal contract to the type system.
120    ///
121    /// # Errors
122    ///
123    /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
124    ///   if the bound session has no primary account for
125    ///   `urn:ietf:params:jmap:mail`.
126    /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
127    ///   if `update` is `Some` and `serde_json::to_value` fails on the
128    ///   patch map (pathological conditions only; see
129    ///   [`Self::email_set`] for the memory-cost discussion that applies
130    ///   identically here).
131    /// - Any transport / protocol variant returned by
132    ///   [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
133    ///   the matching error list on [`Self::identity_get`].
134    pub async fn identity_set(
135        &self,
136        create: Option<serde_json::Value>,
137        update: Option<HashMap<Id, PatchObject>>,
138        destroy: Option<Vec<Id>>,
139    ) -> Result<SetResponse<jmap_mail_types::Identity>, jmap_base_client::ClientError> {
140        if create.is_none() && update.is_none() && destroy.is_none() {
141            return Err(jmap_base_client::ClientError::InvalidArgument(
142                "identity_set: at least one of create, update, destroy must be Some \
143                 (an all-None /set is a no-op round-trip)"
144                    .into(),
145            ));
146        }
147        let (api_url, account_id) = self.session_parts()?;
148        let mut args = serde_json::json!({
149            "accountId": account_id,
150        });
151        if let Some(c) = create {
152            args["create"] = c;
153        }
154        if let Some(u) = update {
155            args["update"] = serde_json::to_value(&u).map_err(|e| {
156                jmap_base_client::ClientError::InvalidArgument(format!(
157                    "identity_set: serializing update map failed: {e}"
158                ))
159            })?;
160        }
161        if let Some(d) = destroy {
162            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
163        }
164        let req = super::build_request("Identity/set", args, super::USING_SUBMISSION);
165        let resp = self.call_internal(api_url, &req).await?;
166        jmap_base_client::extract_response(&resp, super::CALL_ID)
167    }
168}
169
170// ---------------------------------------------------------------------------
171// Tests
172// ---------------------------------------------------------------------------
173
174#[cfg(test)]
175mod tests {
176    use serde_json::json;
177
178    // identity_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
179    // (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
180    // impossible to express through the typed API.
181
182    // The InvalidArgument guard for empty since_state lives in identity_changes
183    // production code; testing it requires a wiremock-backed async harness.
184    // See JMAP-sc1b.64.
185
186    // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
187    //   - identity_get_request_shape
188    //   - identity_set_request_shape
189    // Each hand-built `args = json!({...})` and fed it to `build_request`,
190    // never invoking the `identity_get` / `identity_set` production builders.
191    // Real production-path coverage for these methods is tracked as a
192    // wiremock-smoke gap under JMAP-uuoi (no `tests/identity_*.rs` smoke
193    // file exists yet).
194    //
195    // `build_request`, `CALL_ID`, and `USING_SUBMISSION` themselves have their
196    // own focused tests in `methods/mod.rs`.
197
198    /// Oracle: Identity deserialization from RFC 8621 §6 example.
199    #[test]
200    fn identity_get_response_deserializes() {
201        let json = json!({
202            "accountId": "acc1",
203            "state": "s1",
204            "list": [
205                {
206                    "id": "ident1",
207                    "name": "Jane Doe",
208                    "email": "jane@example.com",
209                    "textSignature": "-- \nJane",
210                    "htmlSignature": "<p>Jane</p>",
211                    "mayDelete": true
212                }
213            ],
214            "notFound": []
215        });
216        use super::super::GetResponse;
217        let resp: GetResponse<jmap_mail_types::Identity> =
218            serde_json::from_value(json).expect("must deserialize Identity GetResponse");
219        assert_eq!(resp.list.len(), 1);
220        assert_eq!(resp.list[0].name, "Jane Doe");
221        assert_eq!(resp.list[0].email, "jane@example.com");
222        assert!(resp.list[0].may_delete);
223    }
224}