diff --git a/.env.template b/.env.template index 425741ae7f..c375851547 100644 --- a/.env.template +++ b/.env.template @@ -72,6 +72,11 @@ # WEBSOCKET_ADDRESS=0.0.0.0 # WEBSOCKET_PORT=3012 +## Enables push notifications (requires key and id from https://bitwarden.com/host) +# PUSH_ENABLED=true +# PUSH_INSTALLATION_ID=CHANGEME +# PUSH_INSTALLATION_KEY=CHANGEME + ## Controls whether users are allowed to create Bitwarden Sends. ## This setting applies globally to all users. ## To control this on a per-org basis instead, use the "Disable Send" org policy. diff --git a/migrations/mysql/2023-02-18-125735_push_uuid_table/down.sql b/migrations/mysql/2023-02-18-125735_push_uuid_table/down.sql new file mode 100644 index 0000000000..e69de29bb2 diff --git a/migrations/mysql/2023-02-18-125735_push_uuid_table/up.sql b/migrations/mysql/2023-02-18-125735_push_uuid_table/up.sql new file mode 100644 index 0000000000..b2a3ea11bd --- /dev/null +++ b/migrations/mysql/2023-02-18-125735_push_uuid_table/up.sql @@ -0,0 +1 @@ +ALTER TABLE devices ADD COLUMN push_uuid TEXT; \ No newline at end of file diff --git a/migrations/postgresql/2023-02-18-125735_push_uuid_table/down.sql b/migrations/postgresql/2023-02-18-125735_push_uuid_table/down.sql new file mode 100644 index 0000000000..e69de29bb2 diff --git a/migrations/postgresql/2023-02-18-125735_push_uuid_table/up.sql b/migrations/postgresql/2023-02-18-125735_push_uuid_table/up.sql new file mode 100644 index 0000000000..b2a3ea11bd --- /dev/null +++ b/migrations/postgresql/2023-02-18-125735_push_uuid_table/up.sql @@ -0,0 +1 @@ +ALTER TABLE devices ADD COLUMN push_uuid TEXT; \ No newline at end of file diff --git a/migrations/sqlite/2023-02-18-125735_push_uuid_table/down.sql b/migrations/sqlite/2023-02-18-125735_push_uuid_table/down.sql new file mode 100644 index 0000000000..e69de29bb2 diff --git a/migrations/sqlite/2023-02-18-125735_push_uuid_table/up.sql b/migrations/sqlite/2023-02-18-125735_push_uuid_table/up.sql new file mode 100644 index 0000000000..b2a3ea11bd --- /dev/null +++ b/migrations/sqlite/2023-02-18-125735_push_uuid_table/up.sql @@ -0,0 +1 @@ +ALTER TABLE devices ADD COLUMN push_uuid TEXT; \ No newline at end of file diff --git a/src/api/admin.rs b/src/api/admin.rs index 6ec71ee312..b836ce36a7 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -13,7 +13,7 @@ use rocket::{ }; use crate::{ - api::{core::log_event, ApiResult, EmptyResult, JsonResult, Notify, NumberOrString}, + api::{core::log_event, unregister_push_device, ApiResult, EmptyResult, JsonResult, Notify, NumberOrString}, auth::{decode_admin, encode_jwt, generate_admin_claims, ClientIp}, config::ConfigBuilder, db::{backup_database, get_sql_server_version, models::*, DbConn, DbConnType}, @@ -396,12 +396,22 @@ async fn delete_user(uuid: &str, token: AdminToken, mut conn: DbConn) -> EmptyRe #[post("/users//deauth")] async fn deauth_user(uuid: &str, _token: AdminToken, mut conn: DbConn, nt: Notify<'_>) -> EmptyResult { let mut user = get_user_or_404(uuid, &mut conn).await?; + + if CONFIG.push_enabled() { + while let Some(d) = Device::find_push_device_by_user(&user.uuid, &mut conn).await { + match unregister_push_device(d.uuid).await { + Ok(r) => r, + Err(e) => error!("Unable to unregister devices from Bitwarden server: {}", e), + }; + } + } + Device::delete_all_by_user(&user.uuid, &mut conn).await?; user.reset_security_stamp(); let save_result = user.save(&mut conn).await; - nt.send_logout(&user, None).await; + nt.send_logout(&user, None, &mut conn).await; save_result } @@ -415,7 +425,7 @@ async fn disable_user(uuid: &str, _token: AdminToken, mut conn: DbConn, nt: Noti let save_result = user.save(&mut conn).await; - nt.send_logout(&user, None).await; + nt.send_logout(&user, None, &mut conn).await; save_result } diff --git a/src/api/core/accounts.rs b/src/api/core/accounts.rs index 159fa38eec..ba1264cc86 100644 --- a/src/api/core/accounts.rs +++ b/src/api/core/accounts.rs @@ -4,7 +4,8 @@ use serde_json::Value; use crate::{ api::{ - core::log_user_event, EmptyResult, JsonResult, JsonUpcase, Notify, NumberOrString, PasswordData, UpdateType, + core::log_user_event, register_push_device, unregister_push_device, EmptyResult, JsonResult, JsonUpcase, + Notify, NumberOrString, PasswordData, UpdateType, }, auth::{decode_delete, decode_invite, decode_verify_email, Headers}, crypto, @@ -35,6 +36,7 @@ pub fn routes() -> Vec { post_verify_email_token, post_delete_recover, post_delete_recover_token, + post_device_token, delete_account, post_delete_account, revision_date, @@ -46,6 +48,9 @@ pub fn routes() -> Vec { get_known_device, get_known_device_from_path, put_avatar, + put_device_token, + clear_device_token, + clear_device_token_post, ] } @@ -338,7 +343,7 @@ async fn post_password( // Prevent loging out the client where the user requested this endpoint from. // If you do logout the user it will causes issues at the client side. // Adding the device uuid will prevent this. - nt.send_logout(&user, Some(headers.device.uuid)).await; + nt.send_logout(&user, Some(headers.device.uuid), &mut conn).await; save_result } @@ -398,7 +403,7 @@ async fn post_kdf(data: JsonUpcase, headers: Headers, mut conn: D user.set_password(&data.NewMasterPasswordHash, Some(data.Key), true, None); let save_result = user.save(&mut conn).await; - nt.send_logout(&user, Some(headers.device.uuid)).await; + nt.send_logout(&user, Some(headers.device.uuid.clone()), &mut conn).await; save_result } @@ -485,7 +490,7 @@ async fn post_rotatekey(data: JsonUpcase, headers: Headers, mut conn: D // Prevent loging out the client where the user requested this endpoint from. // If you do logout the user it will causes issues at the client side. // Adding the device uuid will prevent this. - nt.send_logout(&user, Some(headers.device.uuid)).await; + nt.send_logout(&user, Some(headers.device.uuid.clone()), &mut conn).await; save_result } @@ -508,7 +513,7 @@ async fn post_sstamp( user.reset_security_stamp(); let save_result = user.save(&mut conn).await; - nt.send_logout(&user, None).await; + nt.send_logout(&user, None, &mut conn).await; save_result } @@ -611,7 +616,7 @@ async fn post_email( let save_result = user.save(&mut conn).await; - nt.send_logout(&user, None).await; + nt.send_logout(&user, None, &mut conn).await; save_result } @@ -930,3 +935,69 @@ impl<'r> FromRequest<'r> for KnownDevice { }) } } + +#[derive(Deserialize)] +#[allow(non_snake_case)] +struct PushToken { + PushToken: String, +} + +#[post("/devices/identifier//token", data = "")] +async fn post_device_token(uuid: String, data: JsonUpcase, headers: Headers, conn: DbConn) -> EmptyResult { + put_device_token(uuid, data, headers, conn).await +} + +#[put("/devices/identifier//token", data = "")] +async fn put_device_token( + uuid: String, + data: JsonUpcase, + headers: Headers, + mut conn: DbConn, +) -> EmptyResult { + if !CONFIG.push_enabled() { + return Ok(()); + } + + let data = data.into_inner().data; + let token = data.PushToken; + let mut device = match Device::find_by_uuid_and_user(&headers.device.uuid, &headers.user.uuid, &mut conn).await { + Some(device) => device, + None => err!(format!("Error: device {uuid} should be present before a token can be assigned")), + }; + device.push_token = Some(token); + if device.push_uuid.is_none() { + device.push_uuid = Some(uuid::Uuid::new_v4().to_string()); + } + if let Err(e) = device.save(&mut conn).await { + err!(format!("An error occured while trying to save the device push token: {e}")); + } + if let Err(e) = register_push_device(headers.user.uuid, device).await { + err!(format!("An error occured while proceeding registration of a device: {e}")); + } + + Ok(()) +} + +#[put("/devices/identifier//clear-token")] +async fn clear_device_token(uuid: String, mut conn: DbConn) -> EmptyResult { + // This only clears push token + // https://github.com/bitwarden/core/blob/master/src/Api/Controllers/DevicesController.cs#L109 + // https://github.com/bitwarden/core/blob/master/src/Core/Services/Implementations/DeviceService.cs#L37 + // This is somehow not implemented in any app, added it in case it is required + if !CONFIG.push_enabled() { + return Ok(()); + } + + if let Some(device) = Device::find_by_uuid(&uuid, &mut conn).await { + Device::clear_push_token_by_uuid(&uuid, &mut conn).await?; + unregister_push_device(device.uuid).await?; + } + + Ok(()) +} + +// On upstream server, both PUT and POST are declared. +#[post("/devices/identifier//clear-token")] +async fn clear_device_token_post(uuid: String, conn: DbConn) -> EmptyResult { + clear_device_token(uuid, conn).await +} diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index a62700466c..e4266a8877 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -511,10 +511,8 @@ pub async fn update_cipher_from_data( ) .await; } - - nt.send_cipher_update(ut, cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid).await; + nt.send_cipher_update(ut, cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, conn).await; } - Ok(()) } @@ -580,6 +578,7 @@ async fn post_ciphers_import( let mut user = headers.user; user.update_revision(&mut conn).await?; nt.send_user_update(UpdateType::SyncVault, &user).await; + Ok(()) } @@ -1108,6 +1107,7 @@ async fn save_attachment( &cipher, &cipher.update_users_revision(&mut conn).await, &headers.device.uuid, + &mut conn, ) .await; @@ -1393,7 +1393,14 @@ async fn move_cipher_selected( // Move cipher cipher.move_to_folder(data.FolderId.clone(), &user_uuid, &mut conn).await?; - nt.send_cipher_update(UpdateType::SyncCipherUpdate, &cipher, &[user_uuid.clone()], &headers.device.uuid).await; + nt.send_cipher_update( + UpdateType::SyncCipherUpdate, + &cipher, + &[user_uuid.clone()], + &headers.device.uuid, + &mut conn, + ) + .await; } Ok(()) @@ -1474,6 +1481,7 @@ async fn delete_all( user.update_revision(&mut conn).await?; nt.send_user_update(UpdateType::SyncVault, &user).await; + Ok(()) } } @@ -1503,6 +1511,7 @@ async fn _delete_cipher_by_uuid( &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, + conn, ) .await; } else { @@ -1512,6 +1521,7 @@ async fn _delete_cipher_by_uuid( &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, + conn, ) .await; } @@ -1581,8 +1591,10 @@ async fn _restore_cipher_by_uuid(uuid: &str, headers: &Headers, conn: &mut DbCon &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, + conn, ) .await; + if let Some(org_uuid) = &cipher.organization_uuid { log_event( EventType::CipherRestored as i32, @@ -1662,8 +1674,10 @@ async fn _delete_cipher_attachment_by_id( &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, + conn, ) .await; + if let Some(org_uuid) = cipher.organization_uuid { log_event( EventType::CipherAttachmentDeleted as i32, diff --git a/src/api/core/folders.rs b/src/api/core/folders.rs index 7b52bd18f6..3af1285c05 100644 --- a/src/api/core/folders.rs +++ b/src/api/core/folders.rs @@ -50,7 +50,7 @@ async fn post_folders(data: JsonUpcase, headers: Headers, mut conn: let mut folder = Folder::new(headers.user.uuid, data.Name); folder.save(&mut conn).await?; - nt.send_folder_update(UpdateType::SyncFolderCreate, &folder, &headers.device.uuid).await; + nt.send_folder_update(UpdateType::SyncFolderCreate, &folder, &headers.device.uuid, &mut conn).await; Ok(Json(folder.to_json())) } @@ -88,7 +88,7 @@ async fn put_folder( folder.name = data.Name; folder.save(&mut conn).await?; - nt.send_folder_update(UpdateType::SyncFolderUpdate, &folder, &headers.device.uuid).await; + nt.send_folder_update(UpdateType::SyncFolderUpdate, &folder, &headers.device.uuid, &mut conn).await; Ok(Json(folder.to_json())) } @@ -112,6 +112,6 @@ async fn delete_folder(uuid: &str, headers: Headers, mut conn: DbConn, nt: Notif // Delete the actual folder entry folder.delete(&mut conn).await?; - nt.send_folder_update(UpdateType::SyncFolderDelete, &folder, &headers.device.uuid).await; + nt.send_folder_update(UpdateType::SyncFolderDelete, &folder, &headers.device.uuid, &mut conn).await; Ok(()) } diff --git a/src/api/core/mod.rs b/src/api/core/mod.rs index fdf64cd61b..00cfcf8579 100644 --- a/src/api/core/mod.rs +++ b/src/api/core/mod.rs @@ -14,7 +14,6 @@ pub use sends::purge_sends; pub use two_factor::send_incomplete_2fa_notifications; pub fn routes() -> Vec { - let mut device_token_routes = routes![clear_device_token, put_device_token]; let mut eq_domains_routes = routes![get_eq_domains, post_eq_domains, put_eq_domains]; let mut hibp_routes = routes![hibp_breach]; let mut meta_routes = routes![alive, now, version, config]; @@ -28,7 +27,6 @@ pub fn routes() -> Vec { routes.append(&mut organizations::routes()); routes.append(&mut two_factor::routes()); routes.append(&mut sends::routes()); - routes.append(&mut device_token_routes); routes.append(&mut eq_domains_routes); routes.append(&mut hibp_routes); routes.append(&mut meta_routes); @@ -57,37 +55,6 @@ use crate::{ util::get_reqwest_client, }; -#[put("/devices/identifier//clear-token")] -fn clear_device_token(uuid: &str) -> &'static str { - // This endpoint doesn't have auth header - - let _ = uuid; - // uuid is not related to deviceId - - // This only clears push token - // https://github.com/bitwarden/core/blob/master/src/Api/Controllers/DevicesController.cs#L109 - // https://github.com/bitwarden/core/blob/master/src/Core/Services/Implementations/DeviceService.cs#L37 - "" -} - -#[put("/devices/identifier//token", data = "")] -fn put_device_token(uuid: &str, data: JsonUpcase, headers: Headers) -> Json { - let _data: Value = data.into_inner().data; - // Data has a single string value "PushToken" - let _ = uuid; - // uuid is not related to deviceId - - // TODO: This should save the push token, but we don't have push functionality - - Json(json!({ - "Id": headers.device.uuid, - "Name": headers.device.name, - "Type": headers.device.atype, - "Identifier": headers.device.uuid, - "CreationDate": crate::util::format_date(&headers.device.created_at), - })) -} - #[derive(Serialize, Deserialize, Debug)] #[allow(non_snake_case)] struct GlobalDomain { diff --git a/src/api/core/organizations.rs b/src/api/core/organizations.rs index 7c3b41fdac..3899611c18 100644 --- a/src/api/core/organizations.rs +++ b/src/api/core/organizations.rs @@ -2716,7 +2716,7 @@ async fn put_reset_password( user.set_password(reset_request.NewMasterPasswordHash.as_str(), Some(reset_request.Key), true, None); user.save(&mut conn).await?; - nt.send_logout(&user, None).await; + nt.send_logout(&user, None, &mut conn).await; log_event( EventType::OrganizationUserAdminResetPassword as i32, diff --git a/src/api/mod.rs b/src/api/mod.rs index 06db310b60..f3f79210bb 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -3,6 +3,7 @@ pub mod core; mod icons; mod identity; mod notifications; +mod push; mod web; use rocket::serde::json::Json; @@ -22,6 +23,10 @@ pub use crate::api::{ identity::routes as identity_routes, notifications::routes as notifications_routes, notifications::{start_notification_server, Notify, UpdateType}, + push::{ + push_cipher_update, push_folder_update, push_logout, push_send_update, push_user_update, register_push_device, + unregister_push_device, + }, web::catchers as web_catchers, web::routes as web_routes, web::static_files, diff --git a/src/api/notifications.rs b/src/api/notifications.rs index 7bc502eeb1..87dd27bf39 100644 --- a/src/api/notifications.rs +++ b/src/api/notifications.rs @@ -21,7 +21,10 @@ use tokio_tungstenite::{ use crate::{ auth::ClientIp, - db::models::{Cipher, Folder, Send as DbSend, User}, + db::{ + models::{Cipher, Folder, Send as DbSend, User}, + DbConn, + }, Error, CONFIG, }; @@ -33,6 +36,8 @@ static WS_USERS: Lazy> = Lazy::new(|| { }) }); +use super::{push_cipher_update, push_folder_update, push_logout, push_send_update, push_user_update}; + pub fn routes() -> Vec { routes![websockets_hub] } @@ -233,19 +238,33 @@ impl WebSocketUsers { ); self.send_update(&user.uuid, &data).await; + + if CONFIG.push_enabled() { + push_user_update(ut, user).await; + } } - pub async fn send_logout(&self, user: &User, acting_device_uuid: Option) { + pub async fn send_logout(&self, user: &User, acting_device_uuid: Option, conn: &mut DbConn) { let data = create_update( vec![("UserId".into(), user.uuid.clone().into()), ("Date".into(), serialize_date(user.updated_at))], UpdateType::LogOut, - acting_device_uuid, + acting_device_uuid.clone(), ); self.send_update(&user.uuid, &data).await; + + if CONFIG.push_enabled() { + push_logout(user, acting_device_uuid, conn).await; + } } - pub async fn send_folder_update(&self, ut: UpdateType, folder: &Folder, acting_device_uuid: &String) { + pub async fn send_folder_update( + &self, + ut: UpdateType, + folder: &Folder, + acting_device_uuid: &String, + conn: &mut DbConn, + ) { let data = create_update( vec![ ("Id".into(), folder.uuid.clone().into()), @@ -257,6 +276,10 @@ impl WebSocketUsers { ); self.send_update(&folder.user_uuid, &data).await; + + if CONFIG.push_enabled() { + push_folder_update(ut, folder, acting_device_uuid, conn).await; + } } pub async fn send_cipher_update( @@ -265,6 +288,7 @@ impl WebSocketUsers { cipher: &Cipher, user_uuids: &[String], acting_device_uuid: &String, + conn: &mut DbConn, ) { let user_uuid = convert_option(cipher.user_uuid.clone()); let org_uuid = convert_option(cipher.organization_uuid.clone()); @@ -284,6 +308,10 @@ impl WebSocketUsers { for uuid in user_uuids { self.send_update(uuid, &data).await; } + + if CONFIG.push_enabled() && user_uuids.len() == 1 { + push_cipher_update(ut, cipher, acting_device_uuid, conn).await; + } } pub async fn send_send_update(&self, ut: UpdateType, send: &DbSend, user_uuids: &[String]) { @@ -302,6 +330,9 @@ impl WebSocketUsers { for uuid in user_uuids { self.send_update(uuid, &data).await; } + if CONFIG.push_enabled() && user_uuids.len() == 1 { + push_send_update(ut, send).await; + } } } @@ -343,7 +374,7 @@ fn create_ping() -> Vec { } #[allow(dead_code)] -#[derive(Eq, PartialEq)] +#[derive(Copy, Clone, Eq, PartialEq)] pub enum UpdateType { SyncCipherUpdate = 0, SyncCipherCreate = 1, diff --git a/src/api/push.rs b/src/api/push.rs new file mode 100644 index 0000000000..c9d16264fc --- /dev/null +++ b/src/api/push.rs @@ -0,0 +1,296 @@ +use handlebars::JsonValue; +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 { + static PUSH_TOKEN: Lazy> = 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(¶ms).send().await + { + Ok(r) => r, + Err(e) => err!(format!("Error getting push token from bitwarden server: {e}")), + }; + + let json_pushtoken = match res.json::().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; + } + }; + + let device = match Device::find_by_uuid_and_user(acting_device_uuid, user_uuid, conn).await { + Some(d) => d, + None => { + debug!("Device doesn't exist"); + return; + } + }; + + 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, conn: &mut crate::db::DbConn) { + let data: JsonValue; + if let Some(d) = acting_device_uuid { + if let Some(device) = Device::find_by_uuid_and_user(&d, &user.uuid, conn).await { + 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 { + debug!("Device doesn't exist"); + } + } else { + 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, +) { + let device = match Device::find_by_uuid_and_user(acting_device_uuid, &folder.user_uuid, conn).await { + Some(d) => d, + None => { + debug!("Device doesn't exist"); + return; + } + }; + + 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) { + if send.user_uuid.is_none() { + return; + } + + let data = json!({ + "userId": send.user_uuid, + "organizationId": (), + "deviceId": (), + "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); + }; +} diff --git a/src/config.rs b/src/config.rs index 2a42b5f5f6..7351b94168 100644 --- a/src/config.rs +++ b/src/config.rs @@ -377,6 +377,16 @@ make_config! { /// Websocket port websocket_port: u16, false, def, 3012; }, + push { + /// Enable push notifications + push_enabled: bool, false, def, false; + /// Push relay base uri + push_relay_uri: String, false, def, "https://push.bitwarden.com".to_string(); + /// Installation id |> The installation id from https://bitwarden.com/host + push_installation_id: Pass, false, def, String::new(); + /// Installation key |> The installation key from https://bitwarden.com/host + push_installation_key: Pass, false, def, String::new(); + }, jobs { /// Job scheduler poll interval |> How often the job scheduler thread checks for jobs to run. /// Set to 0 to globally disable scheduled jobs. @@ -724,6 +734,17 @@ fn validate_config(cfg: &ConfigItems) -> Result<(), Error> { } } + if cfg.push_enabled && (cfg.push_installation_id == String::new() || cfg.push_installation_key == String::new()) { + err!( + "Misconfigured Push Notification service\n\ + ########################################################################################\n\ + # It looks like you enabled Push Notification feature, but didn't configure it #\n\ + # properly. Make sure the installation id and key from https://bitwarden.com/host are #\n\ + # added to your configuration. #\n\ + ########################################################################################\n" + ) + } + if cfg._enable_duo && (cfg.duo_host.is_some() || cfg.duo_ikey.is_some() || cfg.duo_skey.is_some()) && !(cfg.duo_host.is_some() && cfg.duo_ikey.is_some() && cfg.duo_skey.is_some()) diff --git a/src/db/models/device.rs b/src/db/models/device.rs index e47ccadcb8..fe0b03aaad 100644 --- a/src/db/models/device.rs +++ b/src/db/models/device.rs @@ -15,7 +15,8 @@ db_object! { pub user_uuid: String, pub name: String, - pub atype: i32, // https://github.com/bitwarden/server/blob/master/src/Core/Enums/DeviceType.cs + pub atype: i32, // https://github.com/bitwarden/server/blob/master/src/Core/Enums/DeviceType.cs + pub push_uuid: Option, pub push_token: Option, pub refresh_token: String, @@ -38,6 +39,7 @@ impl Device { name, atype, + push_uuid: None, push_token: None, refresh_token: String::new(), twofactor_remember: None, @@ -155,6 +157,25 @@ impl Device { }} } + pub async fn find_by_uuid(uuid: &str, conn: &mut DbConn) -> Option { + db_run! { conn: { + devices::table + .filter(devices::uuid.eq(uuid)) + .first::(conn) + .ok() + .from_db() + }} + } + + pub async fn clear_push_token_by_uuid(uuid: &str, conn: &mut DbConn) -> EmptyResult { + db_run! { conn: { + diesel::update(devices::table) + .filter(devices::uuid.eq(uuid)) + .set(devices::push_token.eq::>(None)) + .execute(conn) + .map_res("Error removing push token") + }} + } pub async fn find_by_refresh_token(refresh_token: &str, conn: &mut DbConn) -> Option { db_run! { conn: { devices::table @@ -175,4 +196,15 @@ impl Device { .from_db() }} } + pub async fn find_push_device_by_user(user_uuid: &str, conn: &mut DbConn) -> Option { + db_run! { conn: { + devices::table + .filter(devices::user_uuid.eq(user_uuid)) + .filter(devices::push_token.is_not_null()) + .order(devices::updated_at.desc()) + .first::(conn) + .ok() + .from_db() + }} + } } diff --git a/src/db/schemas/mysql/schema.rs b/src/db/schemas/mysql/schema.rs index da51799a29..315f4953c2 100644 --- a/src/db/schemas/mysql/schema.rs +++ b/src/db/schemas/mysql/schema.rs @@ -49,6 +49,7 @@ table! { user_uuid -> Text, name -> Text, atype -> Integer, + push_uuid -> Nullable, push_token -> Nullable, refresh_token -> Text, twofactor_remember -> Nullable, diff --git a/src/db/schemas/postgresql/schema.rs b/src/db/schemas/postgresql/schema.rs index aef644921c..c42e8d18e9 100644 --- a/src/db/schemas/postgresql/schema.rs +++ b/src/db/schemas/postgresql/schema.rs @@ -49,6 +49,7 @@ table! { user_uuid -> Text, name -> Text, atype -> Integer, + push_uuid -> Nullable, push_token -> Nullable, refresh_token -> Text, twofactor_remember -> Nullable, diff --git a/src/db/schemas/sqlite/schema.rs b/src/db/schemas/sqlite/schema.rs index a30b74338f..402f0a222d 100644 --- a/src/db/schemas/sqlite/schema.rs +++ b/src/db/schemas/sqlite/schema.rs @@ -49,6 +49,7 @@ table! { user_uuid -> Text, name -> Text, atype -> Integer, + push_uuid -> Nullable, push_token -> Nullable, refresh_token -> Text, twofactor_remember -> Nullable,