summaryrefslogtreecommitdiff
path: root/crates/jmap/src/push/get.rs
blob: c3d35eaa7feb68ef113e1d88dba8b94acdce78e5 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use base64::{engine::general_purpose, Engine};
use jmap_proto::{
    error::method::MethodError,
    method::get::{GetRequest, GetResponse, RequestArguments},
    object::Object,
    types::{collection::Collection, property::Property, type_state::DataType, value::Value},
};
use store::{
    write::{now, ValueClass},
    BitmapKey, ValueKey,
};
use utils::map::bitmap::Bitmap;

use crate::{auth::AccessToken, services::state, JMAP};

use super::{EncryptionKeys, PushSubscription, UpdateSubscription};

impl JMAP {
    pub async fn push_subscription_get(
        &self,
        mut request: GetRequest<RequestArguments>,
        access_token: &AccessToken,
    ) -> trc::Result<GetResponse> {
        let ids = request.unwrap_ids(self.core.jmap.get_max_objects)?;
        let properties = request.unwrap_properties(&[
            Property::Id,
            Property::DeviceClientId,
            Property::VerificationCode,
            Property::Expires,
            Property::Types,
        ]);
        let account_id = access_token.primary_id();
        let push_ids = self
            .get_document_ids(account_id, Collection::PushSubscription)
            .await?
            .unwrap_or_default();
        let ids = if let Some(ids) = ids {
            ids
        } else {
            push_ids
                .iter()
                .take(self.core.jmap.get_max_objects)
                .map(Into::into)
                .collect::<Vec<_>>()
        };
        let mut response = GetResponse {
            account_id: None,
            state: None,
            list: Vec::with_capacity(ids.len()),
            not_found: vec![],
        };

        for id in ids {
            // Obtain the push subscription object
            let document_id = id.document_id();
            if !push_ids.contains(document_id) {
                response.not_found.push(id.into());
                continue;
            }
            let mut push = if let Some(push) = self
                .get_property::<Object<Value>>(
                    account_id,
                    Collection::PushSubscription,
                    document_id,
                    Property::Value,
                )
                .await?
            {
                push
            } else {
                response.not_found.push(id.into());
                continue;
            };
            let mut result = Object::with_capacity(properties.len());
            for property in &properties {
                match property {
                    Property::Id => {
                        result.append(Property::Id, Value::Id(id));
                    }
                    Property::Url | Property::Keys | Property::Value => {
                        return Err(MethodError::Forbidden(
                            "The 'url' and 'keys' properties are not readable".to_string(),
                        )
                        .into());
                    }
                    property => {
                        result.append(property.clone(), push.remove(property));
                    }
                }
            }
            response.list.push(result);
        }

        Ok(response)
    }

    pub async fn fetch_push_subscriptions(&self, account_id: u32) -> trc::Result<state::Event> {
        let mut subscriptions = Vec::new();
        let document_ids = self
            .core
            .storage
            .data
            .get_bitmap(BitmapKey::document_ids(
                account_id,
                Collection::PushSubscription,
            ))
            .await?
            .unwrap_or_default();

        let current_time = now();

        for document_id in document_ids {
            let mut subscription = self
                .core
                .storage
                .data
                .get_value::<Object<Value>>(ValueKey {
                    account_id,
                    collection: Collection::PushSubscription.into(),
                    document_id,
                    class: ValueClass::Property(Property::Value.into()),
                })
                .await?
                .ok_or_else(|| {
                    trc::StoreCause::NotFound
                        .into_err()
                        .caused_by(trc::location!())
                        .document_id(document_id)
                })?;

            let expires = subscription
                .properties
                .get(&Property::Expires)
                .and_then(|p| p.as_date())
                .ok_or_else(|| {
                    trc::StoreCause::Unexpected
                        .caused_by(trc::location!())
                        .document_id(document_id)
                })?
                .timestamp() as u64;
            if expires > current_time {
                let keys = if let Some((auth, p256dh)) = subscription
                    .properties
                    .remove(&Property::Keys)
                    .and_then(|value| value.try_unwrap_object())
                    .and_then(|mut obj| {
                        (
                            obj.properties
                                .remove(&Property::Auth)
                                .and_then(|value| value.try_unwrap_string())?,
                            obj.properties
                                .remove(&Property::P256dh)
                                .and_then(|value| value.try_unwrap_string())?,
                        )
                            .into()
                    }) {
                    EncryptionKeys {
                        p256dh: general_purpose::URL_SAFE
                            .decode(&p256dh)
                            .unwrap_or_default(),
                        auth: general_purpose::URL_SAFE.decode(&auth).unwrap_or_default(),
                    }
                    .into()
                } else {
                    None
                };
                let verification_code = subscription
                    .properties
                    .remove(&Property::Value)
                    .and_then(|p| p.try_unwrap_string())
                    .ok_or_else(|| {
                        trc::StoreCause::Unexpected
                            .caused_by(trc::location!())
                            .document_id(document_id)
                    })?;
                let url = subscription
                    .properties
                    .remove(&Property::Url)
                    .and_then(|p| p.try_unwrap_string())
                    .ok_or_else(|| {
                        trc::StoreCause::Unexpected
                            .caused_by(trc::location!())
                            .document_id(document_id)
                    })?;

                if subscription
                    .properties
                    .get(&Property::VerificationCode)
                    .and_then(|p| p.as_string())
                    .map_or(false, |v| v == verification_code)
                {
                    let types = if let Some(Value::List(value)) =
                        subscription.properties.remove(&Property::Types)
                    {
                        if !value.is_empty() {
                            let mut type_states = Bitmap::new();
                            for type_state in value {
                                if let Some(type_state) = type_state
                                    .as_string()
                                    .and_then(|type_state| DataType::try_from(type_state).ok())
                                {
                                    type_states.insert(type_state);
                                }
                            }
                            type_states
                        } else {
                            Bitmap::all()
                        }
                    } else {
                        Bitmap::all()
                    };

                    // Add verified subscription
                    subscriptions.push(UpdateSubscription::Verified(PushSubscription {
                        id: document_id,
                        url,
                        expires,
                        types,
                        keys,
                    }));
                } else {
                    // Add unverified subscription
                    subscriptions.push(UpdateSubscription::Unverified {
                        id: document_id,
                        url,
                        code: verification_code,
                        keys,
                    });
                }
            }
        }

        Ok(state::Event::UpdateSubscriptions {
            account_id,
            subscriptions,
        })
    }
}