rusmes-jmap 0.1.2

JMAP server for RusMES — RFC 8620/8621 HTTP/JSON mail API with Email, Mailbox, Thread, Blob, EventSource push, and VacationResponse support
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
//! JMAP method handlers

pub mod email;
pub mod email_advanced;
pub(crate) mod email_query_helpers;
pub mod identity;
pub mod mailbox;
pub mod push_subscription;
pub mod search_snippet;
pub mod submission;
pub mod thread;
pub mod vacation;

use crate::blob::BlobStorage;
use crate::types::{JmapError, JmapErrorType, JmapMethodCall, JmapMethodResponse, Principal};
use rusmes_core::transport::NullMailTransport;
use rusmes_storage::backends::filesystem::FilesystemBackend;
use rusmes_storage::StorageBackend;
use std::path::PathBuf;
use std::sync::Arc;

/// Dispatch JMAP method call.
///
/// Method handlers receive `&Principal` so they can enforce that the
/// `accountId` named in the JMAP request belongs to the authenticated
/// caller; mismatches are rejected with `urn:ietf:params:jmap:error:forbidden`.
///
/// Outgoing mail delivery uses a [`NullMailTransport`] by default.  Callers
/// that need real SMTP delivery should construct a dedicated dispatch path
/// with a concrete transport.
pub async fn dispatch_method(
    call: JmapMethodCall,
    capabilities: &[String],
    principal: &Principal,
) -> anyhow::Result<JmapMethodResponse> {
    let method_name = &call.0;
    let call_id = &call.2;

    // PushSubscription methods are handled without per-account state.
    if method_name == "PushSubscription/get" {
        let request = serde_json::from_value(call.1)?;
        let response = push_subscription::push_subscription_get(request, principal).await?;
        return Ok(JmapMethodResponse(
            "PushSubscription/get".to_string(),
            serde_json::to_value(response)?,
            call_id.clone(),
        ));
    }
    if method_name == "PushSubscription/set" {
        let request = serde_json::from_value(call.1)?;
        let response = push_subscription::push_subscription_set(request, principal).await?;
        return Ok(JmapMethodResponse(
            "PushSubscription/set".to_string(),
            serde_json::to_value(response)?,
            call_id.clone(),
        ));
    }

    // Validate method requires proper capability
    if let Err(error) = validate_method_capability(method_name, capabilities) {
        return Ok(JmapMethodResponse(
            "error".to_string(),
            serde_json::to_value(error)?,
            call_id.clone(),
        ));
    }

    // Get storage backend from configured path
    let backend = Arc::new(FilesystemBackend::new(PathBuf::from("/tmp/rusmes/mail")));
    let message_store = backend.message_store();
    let blob_storage = BlobStorage::new();
    let identity_store = identity::FileIdentityStore::new(PathBuf::from("/tmp/rusmes/jmap"));
    let vacation_store = vacation::FileVacationStore::new(PathBuf::from("/tmp/rusmes/data"));
    let submission_store = submission::FileSubmissionStore::new(PathBuf::from("/tmp/rusmes/jmap"));
    let mail_transport = NullMailTransport;

    // Dispatch to the appropriate handler
    match method_name.as_str() {
        // Email methods
        "Email/get" => {
            let request = serde_json::from_value(call.1)?;
            let response = email::email_get(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Email/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/set" => {
            let request = serde_json::from_value(call.1)?;
            let response = email::email_set(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Email/set".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/query" => {
            let request = serde_json::from_value(call.1)?;
            let response = email::email_query(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Email/query".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/changes" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                email_advanced::email_changes(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Email/changes".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/queryChanges" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                email_advanced::email_query_changes(request, message_store.as_ref(), principal)
                    .await?;
            Ok(JmapMethodResponse(
                "Email/queryChanges".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/copy" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                email_advanced::email_copy(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Email/copy".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/import" => {
            let request = serde_json::from_value(call.1)?;
            let response = email_advanced::email_import(
                request,
                message_store.as_ref(),
                &blob_storage,
                principal,
            )
            .await?;
            Ok(JmapMethodResponse(
                "Email/import".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Email/parse" => {
            let request = serde_json::from_value(call.1)?;
            let response = email_advanced::email_parse(
                request,
                message_store.as_ref(),
                &blob_storage,
                principal,
            )
            .await?;
            Ok(JmapMethodResponse(
                "Email/parse".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // EmailSubmission methods
        "EmailSubmission/get" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                submission::email_submission_get(request, message_store.as_ref(), principal)
                    .await?;
            Ok(JmapMethodResponse(
                "EmailSubmission/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "EmailSubmission/set" => {
            let request = serde_json::from_value(call.1)?;
            let ctx = submission::SubmissionContext {
                message_store: message_store.as_ref(),
                submission_store: &submission_store,
                identity_store: &identity_store,
                mail_transport: &mail_transport,
            };
            let response = submission::email_submission_set(request, principal, &ctx).await?;
            Ok(JmapMethodResponse(
                "EmailSubmission/set".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "EmailSubmission/query" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                submission::email_submission_query(request, message_store.as_ref(), principal)
                    .await?;
            Ok(JmapMethodResponse(
                "EmailSubmission/query".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "EmailSubmission/changes" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                submission::email_submission_changes(request, message_store.as_ref(), principal)
                    .await?;
            Ok(JmapMethodResponse(
                "EmailSubmission/changes".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // Mailbox methods
        "Mailbox/get" => {
            let request = serde_json::from_value(call.1)?;
            let response = mailbox::mailbox_get(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Mailbox/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Mailbox/set" => {
            let request = serde_json::from_value(call.1)?;
            let response = mailbox::mailbox_set(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Mailbox/set".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Mailbox/query" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                mailbox::mailbox_query(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Mailbox/query".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Mailbox/changes" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                mailbox::mailbox_changes(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Mailbox/changes".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Mailbox/queryChanges" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                mailbox::mailbox_query_changes(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Mailbox/queryChanges".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // Thread methods
        "Thread/get" => {
            let request = serde_json::from_value(call.1)?;
            let response = thread::thread_get(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Thread/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Thread/changes" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                thread::thread_changes(request, message_store.as_ref(), principal).await?;
            Ok(JmapMethodResponse(
                "Thread/changes".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // SearchSnippet methods
        "SearchSnippet/get" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                search_snippet::search_snippet_get(request, message_store.as_ref(), principal)
                    .await?;
            Ok(JmapMethodResponse(
                "SearchSnippet/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // Identity methods
        "Identity/get" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                identity::identity_get(request, message_store.as_ref(), &identity_store, principal)
                    .await?;
            Ok(JmapMethodResponse(
                "Identity/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Identity/set" => {
            let request = serde_json::from_value(call.1)?;
            let response =
                identity::identity_set(request, message_store.as_ref(), &identity_store, principal)
                    .await?;
            Ok(JmapMethodResponse(
                "Identity/set".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "Identity/changes" => {
            let request = serde_json::from_value(call.1)?;
            let response = identity::identity_changes(
                request,
                message_store.as_ref(),
                &identity_store,
                principal,
            )
            .await?;
            Ok(JmapMethodResponse(
                "Identity/changes".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        // VacationResponse methods
        "VacationResponse/get" => {
            let request = serde_json::from_value(call.1)?;
            let response = vacation::vacation_response_get(
                request,
                message_store.as_ref(),
                principal,
                &vacation_store,
            )
            .await?;
            Ok(JmapMethodResponse(
                "VacationResponse/get".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }
        "VacationResponse/set" => {
            let request = serde_json::from_value(call.1)?;
            let response = vacation::vacation_response_set(
                request,
                message_store.as_ref(),
                principal,
                &vacation_store,
            )
            .await?;
            Ok(JmapMethodResponse(
                "VacationResponse/set".to_string(),
                serde_json::to_value(response)?,
                call_id.clone(),
            ))
        }

        _ => {
            // Return unknownMethod error
            Ok(JmapMethodResponse(
                "error".to_string(),
                serde_json::to_value(
                    JmapError::new(JmapErrorType::UnknownMethod)
                        .with_detail(format!("Unknown method: {}", method_name)),
                )?,
                call_id.clone(),
            ))
        }
    }
}

/// Validate that the method is supported by the declared capabilities
fn validate_method_capability(method_name: &str, capabilities: &[String]) -> Result<(), JmapError> {
    let required_capability = match method_name {
        m if m.starts_with("Email/") => "urn:ietf:params:jmap:mail",
        m if m.starts_with("Mailbox/") => "urn:ietf:params:jmap:mail",
        m if m.starts_with("Thread/") => "urn:ietf:params:jmap:mail",
        m if m.starts_with("SearchSnippet/") => "urn:ietf:params:jmap:mail",
        m if m.starts_with("EmailSubmission/") => "urn:ietf:params:jmap:submission",
        m if m.starts_with("Identity/") => "urn:ietf:params:jmap:submission",
        m if m.starts_with("VacationResponse/") => "urn:ietf:params:jmap:vacationresponse",
        // PushSubscription is a core RFC 8620 method — only core capability required.
        m if m.starts_with("PushSubscription/") => {
            return Ok(());
        }
        _ => {
            // Core methods don't require additional capabilities beyond core
            return Ok(());
        }
    };

    if !capabilities.iter().any(|cap| cap == required_capability) {
        return Err(
            JmapError::new(JmapErrorType::UnknownMethod).with_detail(format!(
                "Method '{}' requires capability '{}' which was not declared in 'using'",
                method_name, required_capability
            )),
        );
    }

    Ok(())
}

/// Helper used by every method handler: assert that `requested_account_id`
/// matches the principal's owned account and return a [`ForbiddenError`]
/// otherwise. The error converts cleanly into `anyhow::Error` via the
/// `?` operator.
pub(crate) fn ensure_account_ownership(
    requested_account_id: &str,
    principal: &Principal,
) -> Result<(), ForbiddenError> {
    if principal.owns_account(requested_account_id) {
        Ok(())
    } else {
        tracing::warn!(
            "JMAP account ownership mismatch: principal {} attempted to access account {}",
            principal.username,
            requested_account_id
        );
        Err(ForbiddenError {
            requested_account_id: requested_account_id.to_string(),
            principal_account_id: principal.account_id.clone(),
        })
    }
}

/// Strongly-typed ownership-mismatch error returned by individual method
/// handlers. Implements `From` into `anyhow::Error` via [`std::error::Error`]
/// so handlers can use `?` directly.
#[derive(Debug, Clone)]
pub struct ForbiddenError {
    /// `accountId` named in the JMAP request.
    pub requested_account_id: String,
    /// `accountId` actually owned by the authenticated [`Principal`].
    pub principal_account_id: String,
}

impl std::fmt::Display for ForbiddenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: requested account '{}' is not owned by principal (owns '{}')",
            JmapErrorType::Forbidden.as_str(),
            self.requested_account_id,
            self.principal_account_id
        )
    }
}

impl std::error::Error for ForbiddenError {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Principal;

    fn alice() -> Principal {
        Principal {
            username: "alice".to_string(),
            account_id: "account-alice".to_string(),
            scopes: vec![],
        }
    }

    #[test]
    fn ensure_ownership_ok() {
        let p = alice();
        assert!(ensure_account_ownership("account-alice", &p).is_ok());
    }

    #[test]
    fn ensure_ownership_rejected() {
        let p = alice();
        let err = ensure_account_ownership("account-bob", &p).expect_err("should reject");
        assert_eq!(err.requested_account_id, "account-bob");
        assert_eq!(err.principal_account_id, "account-alice");
    }
}