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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! JMAP `PushSubscription/get` and `PushSubscription/set` handlers.
//!
//! Implements RFC 8620 §5.1: clients register a push endpoint URL; the server
//! delivers a verification push, and thereafter fans out `StateChange` events to
//! all verified subscriptions whose `types` list matches the changed data type.
//!
//! # Registry architecture
//!
//! The push registry lives in a `OnceLock<Arc<PushState>>` so the dispatch
//! function (which has no state parameter) can access it without threading the
//! handle through every call site.  Call [`init_push_state`] once at server
//! startup before dispatching any JMAP requests.

use crate::types::{JmapSetError, Principal, PushKeys, PushSubscription};
use crate::web_push::{WebPushClient, WebPushError};
use base64::Engine as _;
use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};

// ──────────────────────────────────────────────────────────────────────────────
// Global push state
// ──────────────────────────────────────────────────────────────────────────────

/// Shared push state accessible from the stateless dispatch function.
pub struct PushState {
    /// Map of subscription ID → subscription.
    pub registry: Arc<DashMap<String, PushSubscription>>,
    /// WebPush HTTP client with loaded VAPID key.
    pub client: Arc<WebPushClient>,
}

static PUSH_STATE: OnceLock<Arc<PushState>> = OnceLock::new();

/// Install the global push state.
///
/// Must be called once at server startup before any `PushSubscription/*`
/// method can be dispatched.  Subsequent calls are no-ops (the first-writer
/// wins, matching the `global_metrics()` pattern).
pub fn init_push_state(state: Arc<PushState>) {
    let _ = PUSH_STATE.set(state);
}

/// Retrieve the global push state, or `None` if it has not been initialised.
pub fn push_state() -> Option<&'static Arc<PushState>> {
    PUSH_STATE.get()
}

/// Registry type alias.
pub type PushRegistry = Arc<DashMap<String, PushSubscription>>;

// ──────────────────────────────────────────────────────────────────────────────
// Request / response types
// ──────────────────────────────────────────────────────────────────────────────

/// `PushSubscription/get` request (RFC 8620 §5.1).
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionGetRequest {
    /// Optional list of subscription IDs to retrieve.  `None` means "all".
    #[serde(default)]
    pub ids: Option<Vec<String>>,
}

/// `PushSubscription/get` response.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionGetResponse {
    pub list: Vec<PushSubscriptionView>,
    pub not_found: Vec<String>,
}

/// The RFC 8620 §5.1 view of a `PushSubscription` returned to the client.
///
/// Fields marked `#[serde(skip)]` on the internal struct are re-exposed only
/// where RFC 8620 says they should appear in API responses.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionView {
    pub id: String,
    pub device_client_id: String,
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keys: Option<PushKeys>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires: Option<chrono::DateTime<chrono::Utc>>,
    pub types: Vec<String>,
}

impl From<&PushSubscription> for PushSubscriptionView {
    fn from(s: &PushSubscription) -> Self {
        Self {
            id: s.id.clone(),
            device_client_id: s.device_client_id.clone(),
            url: s.url.clone(),
            keys: s.keys.clone(),
            expires: s.expires,
            types: s.types.clone(),
        }
    }
}

/// `PushSubscription/set` request.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionSetRequest {
    #[serde(default)]
    pub create: Option<HashMap<String, PushSubscriptionCreate>>,
    #[serde(default)]
    pub update: Option<HashMap<String, PushSubscriptionUpdate>>,
    #[serde(default)]
    pub destroy: Option<Vec<String>>,
}

/// Fields accepted when creating a new push subscription.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionCreate {
    pub device_client_id: String,
    pub url: String,
    #[serde(default)]
    pub keys: Option<PushKeys>,
    #[serde(default)]
    pub expires: Option<chrono::DateTime<chrono::Utc>>,
    #[serde(default)]
    pub types: Vec<String>,
}

/// Fields that may be patched on an existing push subscription.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionUpdate {
    /// Supply the server-issued code to transition the subscription to `verified`.
    #[serde(default)]
    pub verification_code: Option<String>,
    /// Replace the monitored type list.
    #[serde(default)]
    pub types: Option<Vec<String>>,
    /// Update the expiry timestamp.
    #[serde(default)]
    pub expires: Option<chrono::DateTime<chrono::Utc>>,
}

/// `PushSubscription/set` response.
#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionSetResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created: Option<HashMap<String, PushSubscriptionCreated>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated: Option<HashMap<String, Option<serde_json::Value>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destroyed: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_created: Option<HashMap<String, JmapSetError>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_updated: Option<HashMap<String, JmapSetError>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub not_destroyed: Option<HashMap<String, JmapSetError>>,
}

/// Minimal object returned for a newly created subscription.
///
/// Note: RFC 8620 §5.1 specifies that the server sends the `verificationCode`
/// out-of-band to the push endpoint URL; it is included here in the creation
/// response so that test fixtures can retrieve it without inspecting the
/// mock HTTP server.  Production clients should obtain it from the push
/// delivery.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscriptionCreated {
    pub id: String,
    /// The code that must be echoed back via `PushSubscription/set:update` to
    /// verify the subscription.
    pub verification_code: String,
}

// ──────────────────────────────────────────────────────────────────────────────
// Handlers
// ──────────────────────────────────────────────────────────────────────────────

/// Handle `PushSubscription/get`.
pub async fn push_subscription_get(
    request: PushSubscriptionGetRequest,
    principal: &Principal,
) -> anyhow::Result<PushSubscriptionGetResponse> {
    let state = match push_state() {
        Some(s) => s,
        None => {
            // Push not initialised — return empty list.
            return Ok(PushSubscriptionGetResponse {
                list: vec![],
                not_found: vec![],
            });
        }
    };

    let mut list = Vec::new();
    let mut not_found = Vec::new();

    match request.ids {
        None => {
            // Return all subscriptions owned by this principal.
            for entry in state.registry.iter() {
                if entry.value().principal_id == principal.account_id {
                    list.push(PushSubscriptionView::from(entry.value()));
                }
            }
        }
        Some(ids) => {
            for id in ids {
                match state.registry.get(&id) {
                    Some(entry) if entry.value().principal_id == principal.account_id => {
                        list.push(PushSubscriptionView::from(entry.value()));
                    }
                    Some(_) => {
                        // Exists but owned by someone else — treat as not found
                        // (do not reveal existence of foreign subscriptions).
                        not_found.push(id);
                    }
                    None => {
                        not_found.push(id);
                    }
                }
            }
        }
    }

    Ok(PushSubscriptionGetResponse { list, not_found })
}

/// Handle `PushSubscription/set`.
pub async fn push_subscription_set(
    request: PushSubscriptionSetRequest,
    principal: &Principal,
) -> anyhow::Result<PushSubscriptionSetResponse> {
    let state = match push_state() {
        Some(s) => s,
        None => {
            return Err(anyhow::anyhow!(
                "Push subsystem not initialised; call init_push_state() at server startup"
            ));
        }
    };

    let mut response = PushSubscriptionSetResponse::default();

    // ── Create ────────────────────────────────────────────────────────────────
    if let Some(creates) = request.create {
        let mut created = HashMap::new();
        let mut not_created = HashMap::new();

        for (client_id, create) in creates {
            match create_subscription(state, create, principal).await {
                Ok(result) => {
                    created.insert(client_id, result);
                }
                Err(e) => {
                    not_created.insert(
                        client_id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !created.is_empty() {
            response.created = Some(created);
        }
        if !not_created.is_empty() {
            response.not_created = Some(not_created);
        }
    }

    // ── Update ────────────────────────────────────────────────────────────────
    if let Some(updates) = request.update {
        let mut updated = HashMap::new();
        let mut not_updated = HashMap::new();

        for (id, patch) in updates {
            match update_subscription(state, &id, patch, principal) {
                Ok(()) => {
                    updated.insert(id, None);
                }
                Err(e) => {
                    not_updated.insert(
                        id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !updated.is_empty() {
            response.updated = Some(updated);
        }
        if !not_updated.is_empty() {
            response.not_updated = Some(not_updated);
        }
    }

    // ── Destroy ───────────────────────────────────────────────────────────────
    if let Some(destroy_ids) = request.destroy {
        let mut destroyed = Vec::new();
        let mut not_destroyed = HashMap::new();

        for id in destroy_ids {
            match destroy_subscription(state, &id, principal) {
                Ok(()) => {
                    destroyed.push(id);
                }
                Err(e) => {
                    not_destroyed.insert(
                        id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !destroyed.is_empty() {
            response.destroyed = Some(destroyed);
        }
        if !not_destroyed.is_empty() {
            response.not_destroyed = Some(not_destroyed);
        }
    }

    Ok(response)
}

/// Testable variant of [`push_subscription_set`] that accepts an explicit
/// `PushState` rather than reading from the `OnceLock`.
///
/// Use this in integration tests to avoid `OnceLock` contention across
/// parallel test processes.
pub async fn push_subscription_set_with_state(
    request: PushSubscriptionSetRequest,
    principal: &Principal,
    state: &Arc<PushState>,
) -> anyhow::Result<PushSubscriptionSetResponse> {
    let mut response = PushSubscriptionSetResponse::default();

    // ── Create ────────────────────────────────────────────────────────────────
    if let Some(creates) = request.create {
        let mut created = HashMap::new();
        let mut not_created = HashMap::new();

        for (client_id, create) in creates {
            match create_subscription(state, create, principal).await {
                Ok(result) => {
                    created.insert(client_id, result);
                }
                Err(e) => {
                    not_created.insert(
                        client_id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !created.is_empty() {
            response.created = Some(created);
        }
        if !not_created.is_empty() {
            response.not_created = Some(not_created);
        }
    }

    // ── Update ────────────────────────────────────────────────────────────────
    if let Some(updates) = request.update {
        let mut updated = HashMap::new();
        let mut not_updated = HashMap::new();

        for (id, patch) in updates {
            match update_subscription(state, &id, patch, principal) {
                Ok(()) => {
                    updated.insert(id, None);
                }
                Err(e) => {
                    not_updated.insert(
                        id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !updated.is_empty() {
            response.updated = Some(updated);
        }
        if !not_updated.is_empty() {
            response.not_updated = Some(not_updated);
        }
    }

    // ── Destroy ───────────────────────────────────────────────────────────────
    if let Some(destroy_ids) = request.destroy {
        let mut destroyed = Vec::new();
        let mut not_destroyed = HashMap::new();

        for id in destroy_ids {
            match destroy_subscription(state, &id, principal) {
                Ok(()) => {
                    destroyed.push(id);
                }
                Err(e) => {
                    not_destroyed.insert(
                        id,
                        JmapSetError {
                            error_type: "serverFail".to_string(),
                            description: Some(e.to_string()),
                        },
                    );
                }
            }
        }

        if !destroyed.is_empty() {
            response.destroyed = Some(destroyed);
        }
        if !not_destroyed.is_empty() {
            response.not_destroyed = Some(not_destroyed);
        }
    }

    Ok(response)
}

// ──────────────────────────────────────────────────────────────────────────────
// Internal helpers
// ──────────────────────────────────────────────────────────────────────────────

/// Generate a 32-byte random verification code, base64url-encoded.
fn generate_verification_code() -> Result<String, anyhow::Error> {
    let mut buf = [0u8; 32];
    getrandom::fill(&mut buf)
        .map_err(|e| anyhow::anyhow!("RNG failure during verification code generation: {e}"))?;
    Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf))
}

/// Validate that `url` is an acceptable push endpoint URL.
///
/// In production (`cfg(not(feature = "test-push-http"))`): only HTTPS is
/// accepted per RFC 8030 §5.2.
///
/// When the `test-push-http` Cargo feature is enabled: plain HTTP is also
/// accepted so that `wiremock` mock servers (which start on loopback
/// without TLS) can be used as push endpoints in integration tests.
fn validate_push_url(url: &str) -> Result<(), anyhow::Error> {
    if url.starts_with("https://") {
        return Ok(());
    }
    #[cfg(feature = "test-push-http")]
    if url.starts_with("http://") {
        return Ok(());
    }
    Err(anyhow::anyhow!(
        "Push subscription URL must use HTTPS, got: {url}"
    ))
}

async fn create_subscription(
    state: &PushState,
    create: PushSubscriptionCreate,
    principal: &Principal,
) -> anyhow::Result<PushSubscriptionCreated> {
    validate_push_url(&create.url)?;

    let id = uuid::Uuid::new_v4().to_string();
    let verification_code = generate_verification_code()?;

    let sub = PushSubscription {
        id: id.clone(),
        device_client_id: create.device_client_id,
        url: create.url,
        keys: create.keys,
        verification_code: Some(verification_code.clone()),
        expires: create.expires,
        types: create.types,
        verified: false,
        principal_id: principal.account_id.clone(),
    };

    // Attempt to send the verification push.  A failure here is returned as a
    // `serverFail`; the subscription is NOT stored on failure because there is
    // no way to deliver the verification code.
    match state.client.send(&sub, b"").await {
        Ok(()) => {}
        Err(WebPushError::Gone) => {
            return Err(anyhow::anyhow!(
                "Push endpoint returned 410 Gone during verification"
            ));
        }
        Err(e) => {
            return Err(anyhow::anyhow!("Failed to send verification push: {e}"));
        }
    }

    state.registry.insert(id.clone(), sub);

    Ok(PushSubscriptionCreated {
        id,
        verification_code,
    })
}

fn update_subscription(
    state: &PushState,
    id: &str,
    patch: PushSubscriptionUpdate,
    principal: &Principal,
) -> anyhow::Result<()> {
    let mut entry = state
        .registry
        .get_mut(id)
        .ok_or_else(|| anyhow::anyhow!("Subscription not found: {id}"))?;

    if entry.value().principal_id != principal.account_id {
        return Err(anyhow::anyhow!(
            "Subscription {id} not owned by this principal"
        ));
    }

    // Verification code check.
    if let Some(code) = patch.verification_code {
        if entry.value().verification_code.as_deref() == Some(code.as_str()) {
            entry.value_mut().verified = true;
        } else {
            return Err(anyhow::anyhow!(
                "Verification code mismatch for subscription {id}"
            ));
        }
    }

    if let Some(types) = patch.types {
        entry.value_mut().types = types;
    }
    if let Some(expires) = patch.expires {
        entry.value_mut().expires = Some(expires);
    }

    Ok(())
}

fn destroy_subscription(state: &PushState, id: &str, principal: &Principal) -> anyhow::Result<()> {
    // Do ownership check inside a limited scope so the read guard is dropped
    // before we call `remove()`.  Holding a DashMap read guard while calling
    // `remove()` on the same shard deadlocks.
    let owned = {
        match state.registry.get(id) {
            None => return Err(anyhow::anyhow!("Subscription not found: {id}")),
            Some(entry) => entry.value().principal_id == principal.account_id,
        }
        // guard drops here
    };

    if !owned {
        return Err(anyhow::anyhow!(
            "Subscription {id} not owned by this principal"
        ));
    }

    state.registry.remove(id);
    Ok(())
}