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_MAIL)`.
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    /// Pass `properties: None` to return all fields.
22    pub async fn identity_get(
23        &self,
24        ids: Option<&[Id]>,
25        properties: Option<&[&str]>,
26    ) -> Result<GetResponse<jmap_mail_types::Identity>, jmap_base_client::ClientError> {
27        let (api_url, account_id) = self.session_parts()?;
28        // Omit `ids` / `properties` when None — see the matching comment on
29        // `email_get` for the rationale (consistent with set/changes/query).
30        let mut args = serde_json::json!({ "accountId": account_id });
31        if let Some(id_slice) = ids {
32            args["ids"] = serde_json::to_value(id_slice).expect("Id slice Serialize is infallible");
33        }
34        if let Some(props) = properties {
35            args["properties"] = serde_json::Value::Array(
36                props.iter().copied().map(serde_json::Value::from).collect(),
37            );
38        }
39        let req = super::build_request("Identity/get", args, super::USING_MAIL);
40        let resp = self.call_internal(api_url, &req).await?;
41        jmap_base_client::extract_response(&resp, super::CALL_ID)
42    }
43
44    /// Fetch changes to Identity objects since `since_state` (RFC 8621 §6.2 — Identity/changes).
45    pub async fn identity_changes(
46        &self,
47        since_state: &State,
48        max_changes: Option<u64>,
49    ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
50        // Defence-in-depth: see `thread_changes`.
51        if since_state.as_ref().is_empty() {
52            return Err(jmap_base_client::ClientError::InvalidArgument(
53                "identity_changes: since_state may not be empty".into(),
54            ));
55        }
56        let (api_url, account_id) = self.session_parts()?;
57        let mut args = serde_json::json!({
58            "accountId": account_id,
59            "sinceState": since_state,
60        });
61        if let Some(mc) = max_changes {
62            args["maxChanges"] = mc.into();
63        }
64        let req = super::build_request("Identity/changes", args, super::USING_MAIL);
65        let resp = self.call_internal(api_url, &req).await?;
66        jmap_base_client::extract_response(&resp, super::CALL_ID)
67    }
68
69    /// Create, update, or destroy Identity objects (RFC 8621 §6.3 — Identity/set).
70    ///
71    /// Pass `create`, `update`, and/or `destroy` as needed. Pass `None` to omit.
72    ///
73    /// `update` is `Option<HashMap<Id, PatchObject>>` (RFC 8620 §5.3). Wire
74    /// format is unchanged from a plain JSON object because [`PatchObject`]
75    /// is `#[serde(transparent)]`; the typed parameter binds the JSON Pointer
76    /// key + null-leaf removal contract to the type system.
77    pub async fn identity_set(
78        &self,
79        create: Option<serde_json::Value>,
80        update: Option<HashMap<Id, PatchObject>>,
81        destroy: Option<Vec<Id>>,
82    ) -> Result<SetResponse<jmap_mail_types::Identity>, jmap_base_client::ClientError> {
83        let (api_url, account_id) = self.session_parts()?;
84        let mut args = serde_json::json!({
85            "accountId": account_id,
86        });
87        if let Some(c) = create {
88            args["create"] = c;
89        }
90        if let Some(u) = update {
91            args["update"] = serde_json::to_value(&u).map_err(|e| {
92                jmap_base_client::ClientError::InvalidArgument(format!(
93                    "identity_set: serializing update map failed: {e}"
94                ))
95            })?;
96        }
97        if let Some(d) = destroy {
98            args["destroy"] = serde_json::to_value(&d).expect("Id Vec Serialize is infallible");
99        }
100        let req = super::build_request("Identity/set", args, super::USING_MAIL);
101        let resp = self.call_internal(api_url, &req).await?;
102        jmap_base_client::extract_response(&resp, super::CALL_ID)
103    }
104}
105
106// ---------------------------------------------------------------------------
107// Tests
108// ---------------------------------------------------------------------------
109
110#[cfg(test)]
111mod tests {
112    use serde_json::json;
113
114    // identity_get_empty_id_returns_invalid_argument was deleted in JMAP-6by7.2
115    // (typed-Id refactor): under `Option<&[Id]>` the empty-Id case becomes
116    // impossible to express through the typed API.
117
118    // The InvalidArgument guard for empty since_state lives in identity_changes
119    // production code; testing it requires a wiremock-backed async harness.
120    // See JMAP-sc1b.64.
121
122    // Deleted in JMAP-tco1.5 as Pattern E (vacuous inline tests):
123    //   - identity_get_request_shape
124    //   - identity_set_request_shape
125    // Each hand-built `args = json!({...})` and fed it to `build_request`,
126    // never invoking the `identity_get` / `identity_set` production builders.
127    // Real production-path coverage for these methods is tracked as a
128    // wiremock-smoke gap under JMAP-uuoi (no `tests/identity_*.rs` smoke
129    // file exists yet).
130    //
131    // `build_request`, `CALL_ID`, and `USING_MAIL` themselves have their
132    // own focused tests in `methods/mod.rs`.
133
134    /// Oracle: Identity deserialization from RFC 8621 §6 example.
135    #[test]
136    fn identity_get_response_deserializes() {
137        let json = json!({
138            "accountId": "acc1",
139            "state": "s1",
140            "list": [
141                {
142                    "id": "ident1",
143                    "name": "Jane Doe",
144                    "email": "jane@example.com",
145                    "textSignature": "-- \nJane",
146                    "htmlSignature": "<p>Jane</p>",
147                    "mayDelete": true
148                }
149            ],
150            "notFound": []
151        });
152        use super::super::GetResponse;
153        let resp: GetResponse<jmap_mail_types::Identity> =
154            serde_json::from_value(json).expect("must deserialize Identity GetResponse");
155        assert_eq!(resp.list.len(), 1);
156        assert_eq!(resp.list[0].name, "Jane Doe");
157        assert_eq!(resp.list[0].email, "jane@example.com");
158        assert!(resp.list[0].may_delete);
159    }
160}