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

use crate::{
    api::{ApiResult, EmptyResult, UpdateType},
    db::models::{Cipher, Device, Folder, Send, User},
    util::get_reqwest_client,
    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 get_reqwest_client().post("https://identity.bitwarden.com/connect/token").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(user_uuid: String, device: Device) -> EmptyResult {
    if !CONFIG.push_enabled() {
        return Ok(());
    }
    let auth_push_token = get_auth_push_token().await?;

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

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

    get_reqwest_client()
        .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()?;
    Ok(())
}

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

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

    match get_reqwest_client()
        .delete(CONFIG.push_relay_uri() + "/push/" + &uuid)
        .header(AUTHORIZATION, auth_header)
        .send()
        .await
    {
        Ok(r) => r,
        Err(e) => err!(format!("An error occured 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;
        }
    };

    for device in Device::find_by_user(user_uuid, conn).await {
        let data = json!({
            "userId": user_uuid,
            "organizationId": (),
            "deviceId": device.push_uuid,
            "identifier": acting_device_uuid,
            "type": ut as i32,
            "payload": {
                "Id": cipher.uuid,
                "UserId": cipher.user_uuid,
                "OrganizationId": (),
                "RevisionDate": cipher.updated_at
            }
        });

        send_to_push_relay(data).await;
    }
}

pub async fn push_logout(user: &User, acting_device_uuid: Option<String>, conn: &mut crate::db::DbConn) {
    if let Some(d) = acting_device_uuid {
        for device in Device::find_by_user(&user.uuid, conn).await {
            let data = json!({
                "userId": user.uuid,
                "organizationId": (),
                "deviceId": device.push_uuid,
                "identifier": d,
                "type": UpdateType::LogOut as i32,
                "payload": {
                    "UserId": user.uuid,
                    "Date": user.updated_at
                }
            });
            send_to_push_relay(data).await;
        }
    } else {
        let data = json!({
            "userId": user.uuid,
            "organizationId": (),
            "deviceId": (),
            "identifier": (),
            "type": UpdateType::LogOut as i32,
            "payload": {
                "UserId": user.uuid,
                "Date": user.updated_at
            }
        });
        send_to_push_relay(data).await;
    }
}

pub async fn push_user_update(ut: UpdateType, user: &User) {
    let data = json!({
        "userId": user.uuid,
        "organizationId": (),
        "deviceId": (),
        "identifier": (),
        "type": ut as i32,
        "payload": {
            "UserId": user.uuid,
            "Date": user.updated_at
        }
    });

    send_to_push_relay(data).await;
}

pub async fn push_folder_update(
    ut: UpdateType,
    folder: &Folder,
    acting_device_uuid: &String,
    conn: &mut crate::db::DbConn,
) {
    for device in Device::find_by_user(&folder.user_uuid, conn).await {
        let data = json!({
            "userId": folder.user_uuid,
            "organizationId": (),
            "deviceId": device.push_uuid,
            "identifier": acting_device_uuid,
            "type": ut as i32,
            "payload": {
                "Id": folder.uuid,
                "UserId": folder.user_uuid,
                "RevisionDate": folder.updated_at
            }
        });

        send_to_push_relay(data).await;
    }
}

pub async fn push_send_update(ut: UpdateType, send: &Send, conn: &mut crate::db::DbConn) {
    if let Some(s) = &send.user_uuid {
        for device in Device::find_by_user(s, conn).await {
            let data = json!({
                "userId": send.user_uuid,
                "organizationId": (),
                "deviceId": device.push_uuid,
                "identifier": (),
                "type": ut as i32,
                "payload": {
                    "Id": send.uuid,
                    "UserId": send.user_uuid,
                    "RevisionDate": send.revision_date
                }
            });

            send_to_push_relay(data).await;
        }
    }
}

async fn send_to_push_relay(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);

    if let Err(e) = get_reqwest_client()
        .post(CONFIG.push_relay_uri() + "/push/send")
        .header(ACCEPT, "application/json")
        .header(CONTENT_TYPE, "application/json")
        .header(AUTHORIZATION, auth_header)
        .json(&data)
        .send()
        .await
    {
        error!("An error occured while sending a send update to the push relay: {}", e);
    };
}