aboutsummaryrefslogtreecommitdiff
path: root/src/api/push.rs
blob: eaf304f909e147c2f703f9b8de4bc56db9daa5a6 (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
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
use reqwest::{
    header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE},
    Method,
};
use serde_json::Value;
use tokio::sync::RwLock;

use crate::{
    api::{ApiResult, EmptyResult, UpdateType},
    db::models::{Cipher, Device, Folder, Send, User},
    http_client::make_http_request,
    CONFIG,
};

use once_cell::sync::Lazy;
use std::time::{Duration, Instant};

#[derive(Deserialize)]
struct AuthPushToken {
    access_token: String,
    expires_in: i32,
}

#[derive(Debug)]
struct LocalAuthPushToken {
    access_token: String,
    valid_until: Instant,
}

async fn get_auth_push_token() -> ApiResult<String> {
    static PUSH_TOKEN: Lazy<RwLock<LocalAuthPushToken>> = Lazy::new(|| {
        RwLock::new(LocalAuthPushToken {
            access_token: String::new(),
            valid_until: Instant::now(),
        })
    });
    let push_token = PUSH_TOKEN.read().await;

    if push_token.valid_until.saturating_duration_since(Instant::now()).as_secs() > 0 {
        debug!("Auth Push token still valid, no need for a new one");
        return Ok(push_token.access_token.clone());
    }
    drop(push_token); // Drop the read lock now

    let installation_id = CONFIG.push_installation_id();
    let client_id = format!("installation.{installation_id}");
    let client_secret = CONFIG.push_installation_key();

    let params = [
        ("grant_type", "client_credentials"),
        ("scope", "api.push"),
        ("client_id", &client_id),
        ("client_secret", &client_secret),
    ];

    let res = match make_http_request(Method::POST, &format!("{}/connect/token", CONFIG.push_identity_uri()))?
        .form(&params)
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => err!(format!("Error getting push token from bitwarden server: {e}")),
    };

    let json_pushtoken = match res.json::<AuthPushToken>().await {
        Ok(r) => r,
        Err(e) => err!(format!("Unexpected push token received from bitwarden server: {e}")),
    };

    let mut push_token = PUSH_TOKEN.write().await;
    push_token.valid_until = Instant::now()
        .checked_add(Duration::new((json_pushtoken.expires_in / 2) as u64, 0)) // Token valid for half the specified time
        .unwrap();

    push_token.access_token = json_pushtoken.access_token;

    debug!("Token still valid for {}", push_token.valid_until.saturating_duration_since(Instant::now()).as_secs());
    Ok(push_token.access_token.clone())
}

pub async fn register_push_device(device: &mut Device, conn: &mut crate::db::DbConn) -> EmptyResult {
    if !CONFIG.push_enabled() || !device.is_push_device() || device.is_registered() {
        return Ok(());
    }

    if device.push_token.is_none() {
        warn!("Skipping the registration of the device {} because the push_token field is empty.", device.uuid);
        warn!("To get rid of this message you need to clear the app data and reconnect the device.");
        return Ok(());
    }

    debug!("Registering Device {}", device.uuid);

    // generate a random push_uuid so we know the device is registered
    device.push_uuid = Some(uuid::Uuid::new_v4().to_string());

    //Needed to register a device for push to bitwarden :
    let data = json!({
        "userId": device.user_uuid,
        "deviceId": device.push_uuid,
        "identifier": device.uuid,
        "type": device.atype,
        "pushToken": device.push_token
    });

    let auth_push_token = get_auth_push_token().await?;
    let auth_header = format!("Bearer {}", &auth_push_token);

    if let Err(e) = make_http_request(Method::POST, &(CONFIG.push_relay_uri() + "/push/register"))?
        .header(CONTENT_TYPE, "application/json")
        .header(ACCEPT, "application/json")
        .header(AUTHORIZATION, auth_header)
        .json(&data)
        .send()
        .await?
        .error_for_status()
    {
        err!(format!("An error occurred while proceeding registration of a device: {e}"));
    }

    if let Err(e) = device.save(conn).await {
        err!(format!("An error occurred while trying to save the (registered) device push uuid: {e}"));
    }

    Ok(())
}

pub async fn unregister_push_device(push_uuid: Option<String>) -> EmptyResult {
    if !CONFIG.push_enabled() || push_uuid.is_none() {
        return Ok(());
    }
    let auth_push_token = get_auth_push_token().await?;

    let auth_header = format!("Bearer {}", &auth_push_token);

    match make_http_request(Method::DELETE, &(CONFIG.push_relay_uri() + "/push/" + &push_uuid.unwrap()))?
        .header(AUTHORIZATION, auth_header)
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => err!(format!("An error occurred during device unregistration: {e}")),
    };
    Ok(())
}

pub async fn push_cipher_update(
    ut: UpdateType,
    cipher: &Cipher,
    acting_device_uuid: &String,
    conn: &mut crate::db::DbConn,
) {
    // We shouldn't send a push notification on cipher update if the cipher belongs to an organization, this isn't implemented in the upstream server too.
    if cipher.organization_uuid.is_some() {
        return;
    };
    let user_uuid = match &cipher.user_uuid {
        Some(c) => c,
        None => {
            debug!("Cipher has no uuid");
            return;
        }
    };

    if Device::check_user_has_push_device(user_uuid, conn).await {
        send_to_push_relay(json!({
            "userId": user_uuid,
            "organizationId": (),
            "deviceId": acting_device_uuid,
            "identifier": acting_device_uuid,
            "type": ut as i32,
            "payload": {
                "id": cipher.uuid,
                "userId": cipher.user_uuid,
                "organizationId": (),
                "revisionDate": cipher.updated_at
            }
        }))
        .await;
    }
}

pub fn push_logout(user: &User, acting_device_uuid: Option<String>) {
    let acting_device_uuid: Value = acting_device_uuid.map(|v| v.into()).unwrap_or_else(|| Value::Null);

    tokio::task::spawn(send_to_push_relay(json!({
        "userId": user.uuid,
        "organizationId": (),
        "deviceId": acting_device_uuid,
        "identifier": acting_device_uuid,
        "type": UpdateType::LogOut as i32,
        "payload": {
            "userId": user.uuid,
            "date": user.updated_at
        }
    })));
}

pub fn push_user_update(ut: UpdateType, user: &User) {
    tokio::task::spawn(send_to_push_relay(json!({
        "userId": user.uuid,
        "organizationId": (),
        "deviceId": (),
        "identifier": (),
        "type": ut as i32,
        "payload": {
            "userId": user.uuid,
            "date": user.updated_at
        }
    })));
}

pub async fn push_folder_update(
    ut: UpdateType,
    folder: &Folder,
    acting_device_uuid: &String,
    conn: &mut crate::db::DbConn,
) {
    if Device::check_user_has_push_device(&folder.user_uuid, conn).await {
        tokio::task::spawn(send_to_push_relay(json!({
            "userId": folder.user_uuid,
            "organizationId": (),
            "deviceId": acting_device_uuid,
            "identifier": acting_device_uuid,
            "type": ut as i32,
            "payload": {
                "id": folder.uuid,
                "userId": folder.user_uuid,
                "revisionDate": folder.updated_at
            }
        })));
    }
}

pub async fn push_send_update(ut: UpdateType, send: &Send, acting_device_uuid: &String, conn: &mut crate::db::DbConn) {
    if let Some(s) = &send.user_uuid {
        if Device::check_user_has_push_device(s, conn).await {
            tokio::task::spawn(send_to_push_relay(json!({
                "userId": send.user_uuid,
                "organizationId": (),
                "deviceId": acting_device_uuid,
                "identifier": acting_device_uuid,
                "type": ut as i32,
                "payload": {
                    "id": send.uuid,
                    "userId": send.user_uuid,
                    "revisionDate": send.revision_date
                }
            })));
        }
    }
}

async fn send_to_push_relay(notification_data: Value) {
    if !CONFIG.push_enabled() {
        return;
    }

    let auth_push_token = match get_auth_push_token().await {
        Ok(s) => s,
        Err(e) => {
            debug!("Could not get the auth push token: {}", e);
            return;
        }
    };

    let auth_header = format!("Bearer {}", &auth_push_token);

    let req = match make_http_request(Method::POST, &(CONFIG.push_relay_uri() + "/push/send")) {
        Ok(r) => r,
        Err(e) => {
            error!("An error occurred while sending a send update to the push relay: {}", e);
            return;
        }
    };

    if let Err(e) = req
        .header(ACCEPT, "application/json")
        .header(CONTENT_TYPE, "application/json")
        .header(AUTHORIZATION, &auth_header)
        .json(&notification_data)
        .send()
        .await
    {
        error!("An error occurred while sending a send update to the push relay: {}", e);
    };
}

pub async fn push_auth_request(user_uuid: String, auth_request_uuid: String, conn: &mut crate::db::DbConn) {
    if Device::check_user_has_push_device(user_uuid.as_str(), conn).await {
        tokio::task::spawn(send_to_push_relay(json!({
            "userId": user_uuid,
            "organizationId": (),
            "deviceId": null,
            "identifier": null,
            "type": UpdateType::AuthRequest as i32,
            "payload": {
                "id": auth_request_uuid,
                "userId": user_uuid,
            }
        })));
    }
}

pub async fn push_auth_response(
    user_uuid: String,
    auth_request_uuid: String,
    approving_device_uuid: String,
    conn: &mut crate::db::DbConn,
) {
    if Device::check_user_has_push_device(user_uuid.as_str(), conn).await {
        tokio::task::spawn(send_to_push_relay(json!({
            "userId": user_uuid,
            "organizationId": (),
            "deviceId": approving_device_uuid,
            "identifier": approving_device_uuid,
            "type": UpdateType::AuthRequestResponse as i32,
            "payload": {
                "id": auth_request_uuid,
                "userId": user_uuid,
            }
        })));
    }
}