diff --git a/.env.template b/.env.template index 9d6f75a147..2cabd7c2d9 100644 --- a/.env.template +++ b/.env.template @@ -72,6 +72,12 @@ # WEBSOCKET_ADDRESS=0.0.0.0 # WEBSOCKET_PORT=3012 +## Enables push notifications, get key and id from https://bitwarden.com/host +# PUSH_ENABLED=true +# PUSH_RELAY_URI=https://push.bitwarden.com +# 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 0fd7c2cf08..9577f922a3 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -13,7 +13,10 @@ use rocket::{ }; use crate::{ - api::{core::log_event, ApiResult, EmptyResult, JsonResult, Notify, NumberOrString}, + api::{ + core::log_event, push_logout, 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}, @@ -395,14 +398,21 @@ async fn delete_user(uuid: String, token: AdminToken, mut conn: DbConn) -> Empty #[post("/users//deauth")] async fn deauth_user(uuid: String, _token: AdminToken, mut conn: DbConn, nt: Notify<'_>) -> EmptyResult { let mut user = get_user_or_404(&uuid, &mut conn).await?; - 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; + push_logout(&user, None, &mut conn).await; // Send logout notifications before deleting devices - save_result + match Device::find_push_device_by_user(&user.uuid, &mut conn).await { + Some(d) => { + match unregister_push_device(d.uuid).await { + Ok(r) => r, + Err(e) => error!("Unable to unregister devices from Bitwarden server: {}", e), + }; + } + None => debug!("No device to unregister for {}", &user.email), + }; + Device::delete_all_by_user(&user.uuid, &mut conn).await?; + user.reset_security_stamp(); + user.save(&mut conn).await } #[post("/users//disable")] @@ -415,6 +425,7 @@ async fn disable_user(uuid: String, _token: AdminToken, mut conn: DbConn, nt: No let save_result = user.save(&mut conn).await; nt.send_logout(&user, None).await; + push_logout(&user, None, &mut conn).await; save_result } diff --git a/src/api/core/accounts.rs b/src/api/core/accounts.rs index 7cc1847492..f8d55d74cf 100644 --- a/src/api/core/accounts.rs +++ b/src/api/core/accounts.rs @@ -4,12 +4,15 @@ use serde_json::Value; use crate::{ api::{ - core::log_user_event, EmptyResult, JsonResult, JsonUpcase, Notify, NumberOrString, PasswordData, UpdateType, + core::log_user_event, push_logout, register_push_device, unregister_push_device, EmptyResult, JsonResult, + JsonUpcase, Notify, NumberOrString, PasswordData, UpdateType, }, auth::{decode_delete, decode_invite, decode_verify_email, Headers}, crypto, db::{models::*, DbConn}, - mail, CONFIG, + mail, + //push::{self, push_logout}, + CONFIG, }; use rocket::{ @@ -46,6 +49,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 +344,8 @@ 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.clone())).await; + push_logout(&user, Some(headers.device.uuid.clone()), &mut conn).await; save_result } @@ -395,7 +402,8 @@ 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())).await; + push_logout(&user, Some(headers.device.uuid.clone()), &mut conn).await; save_result } @@ -482,7 +490,8 @@ 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())).await; + push_logout(&user, Some(headers.device.uuid.clone()), &mut conn).await; save_result } @@ -506,6 +515,7 @@ async fn post_sstamp( let save_result = user.save(&mut conn).await; nt.send_logout(&user, None).await; + push_logout(&user, None, &mut conn).await; save_result } @@ -609,6 +619,7 @@ async fn post_email( let save_result = user.save(&mut conn).await; nt.send_logout(&user, None).await; + push_logout(&user, None, &mut conn).await; save_result } @@ -930,3 +941,62 @@ impl<'r> FromRequest<'r> for KnownDevice { }) } } + +#[derive(Deserialize, Debug)] +#[allow(non_snake_case)] +struct PushTokenData { + pushToken: String, +} + +#[put("/devices/identifier//token", data = "")] +async fn put_device_token(uuid: String, data: Json, headers: Headers, mut conn: DbConn) -> EmptyResult { + let data: PushTokenData = data.into_inner(); + let token = data.pushToken.clone(); + let mut device = match Device::find_by_uuid_and_user(&headers.device.uuid, &headers.user.uuid, &mut conn).await { + Some(device) => device, + None => Device::new(uuid, headers.user.uuid.clone(), headers.device.name, headers.device.atype), + }; + 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 { + error!("An error occured while trying to save the device push token: {}", e); + return Err(e); + } + if CONFIG.push_enabled() { + if let Err(e) = register_push_device(headers.user.uuid, device).await { + error!("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) -> &'static str { + // 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 + match Device::delete_token_by_uuid(&uuid, &mut conn).await { + Err(e) => error!("{}", e), + Ok(_r) => (), + }; + let device = match Device::find_by_uuid(&uuid, &mut conn).await { + Some(device) => device, + None => return "", + }; + match unregister_push_device(device.uuid).await { + Err(e) => error!("{}", e), + Ok(_r) => (), + }; + "" +} + +// On upstream server, both PUT and POST are declared. Sadly Rocket doesn't allows to put multiple methods on the same function, so we call the function manually +#[post("/devices/identifier//clear-token")] +async fn clear_device_token_post(uuid: String, conn: DbConn) -> &'static str { + clear_device_token(uuid, conn).await; + "" +} diff --git a/src/api/core/ciphers.rs b/src/api/core/ciphers.rs index 67e2ae39f4..25542a5239 100644 --- a/src/api/core/ciphers.rs +++ b/src/api/core/ciphers.rs @@ -10,7 +10,10 @@ use rocket::{ use serde_json::Value; use crate::{ - api::{self, core::log_event, EmptyResult, JsonResult, JsonUpcase, Notify, PasswordData, UpdateType}, + api::{ + self, core::log_event, push_cipher_update, push_user_update, EmptyResult, JsonResult, JsonUpcase, Notify, + PasswordData, UpdateType, + }, auth::Headers, crypto, db::{models::*, DbConn, DbPool}, @@ -511,10 +514,9 @@ 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 as i32, cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid).await; + push_cipher_update(ut as i32, cipher, &headers.device.uuid, conn).await; } - Ok(()) } @@ -579,7 +581,8 @@ async fn post_ciphers_import( let mut user = headers.user; user.update_revision(&mut conn).await?; - nt.send_user_update(UpdateType::SyncVault, &user).await; + nt.send_user_update(UpdateType::SyncVault as i32, &user).await; + push_user_update(UpdateType::SyncVault as i32, &user).await; Ok(()) } @@ -1103,12 +1106,13 @@ async fn save_attachment( } nt.send_cipher_update( - UpdateType::SyncCipherUpdate, + UpdateType::SyncCipherUpdate as i32, &cipher, &cipher.update_users_revision(&mut conn).await, &headers.device.uuid, ) .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &headers.device.uuid, &mut conn).await; if let Some(org_uuid) = &cipher.organization_uuid { log_event( @@ -1392,7 +1396,9 @@ 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 as i32, &cipher, &[user_uuid.clone()], &headers.device.uuid) + .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &headers.device.uuid, &mut conn).await; } Ok(()) @@ -1439,7 +1445,8 @@ async fn delete_all( Some(user_org) => { if user_org.atype == UserOrgType::Owner { Cipher::delete_all_by_organization(&org_data.org_id, &mut conn).await?; - nt.send_user_update(UpdateType::SyncVault, &user).await; + nt.send_user_update(UpdateType::SyncVault as i32, &user).await; + push_user_update(UpdateType::SyncVault as i32, &user).await; log_event( EventType::OrganizationPurgedVault as i32, @@ -1472,7 +1479,8 @@ async fn delete_all( } user.update_revision(&mut conn).await?; - nt.send_user_update(UpdateType::SyncVault, &user).await; + nt.send_user_update(UpdateType::SyncVault as i32, &user).await; + push_user_update(UpdateType::SyncVault as i32, &user).await; Ok(()) } } @@ -1498,21 +1506,23 @@ async fn _delete_cipher_by_uuid( cipher.deleted_at = Some(Utc::now().naive_utc()); cipher.save(conn).await?; nt.send_cipher_update( - UpdateType::SyncCipherUpdate, + UpdateType::SyncCipherUpdate as i32, &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, ) .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &headers.device.uuid, conn).await; } else { cipher.delete(conn).await?; nt.send_cipher_update( - UpdateType::SyncCipherDelete, + UpdateType::SyncCipherDelete as i32, &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, ) .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &headers.device.uuid, conn).await; } if let Some(org_uuid) = cipher.organization_uuid { @@ -1576,12 +1586,14 @@ async fn _restore_cipher_by_uuid(uuid: &str, headers: &Headers, conn: &mut DbCon cipher.save(conn).await?; nt.send_cipher_update( - UpdateType::SyncCipherUpdate, + UpdateType::SyncCipherUpdate as i32, &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, ) .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &headers.device.uuid, conn).await; + if let Some(org_uuid) = &cipher.organization_uuid { log_event( EventType::CipherRestored as i32, @@ -1657,12 +1669,14 @@ async fn _delete_cipher_attachment_by_id( // Delete attachment attachment.delete(conn).await?; nt.send_cipher_update( - UpdateType::SyncCipherUpdate, + UpdateType::SyncCipherUpdate as i32, &cipher, &cipher.update_users_revision(conn).await, &headers.device.uuid, ) .await; + push_cipher_update(UpdateType::SyncCipherUpdate as i32, &cipher, &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 c27d5455b9..5bcd3a62f8 100644 --- a/src/api/core/folders.rs +++ b/src/api/core/folders.rs @@ -2,7 +2,7 @@ use rocket::serde::json::Json; use serde_json::Value; use crate::{ - api::{EmptyResult, JsonResult, JsonUpcase, Notify, UpdateType}, + api::{push_folder_update, EmptyResult, JsonResult, JsonUpcase, Notify, UpdateType}, auth::Headers, db::{models::*, DbConn}, }; @@ -50,7 +50,8 @@ 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 as i32, &folder, &headers.device.uuid).await; + push_folder_update(UpdateType::SyncFolderCreate as i32, &folder, &headers.device.uuid, &mut conn).await; Ok(Json(folder.to_json())) } @@ -88,7 +89,8 @@ 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 as i32, &folder, &headers.device.uuid).await; + push_folder_update(UpdateType::SyncFolderUpdate as i32, &folder, &headers.device.uuid, &mut conn).await; Ok(Json(folder.to_json())) } @@ -112,6 +114,7 @@ async fn delete_folder(uuid: String, headers: Headers, mut conn: DbConn, nt: Not // 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 as i32, &folder, &headers.device.uuid).await; + push_folder_update(UpdateType::SyncFolderDelete as i32, &folder, &headers.device.uuid, &mut conn).await; Ok(()) } diff --git a/src/api/core/mod.rs b/src/api/core/mod.rs index 6a483842a0..74cabe3f33 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); @@ -50,44 +48,13 @@ use rocket::{serde::json::Json, Catcher, Route}; use serde_json::Value; use crate::{ - api::{JsonResult, JsonUpcase, Notify, UpdateType}, + api::{push_user_update, JsonResult, JsonUpcase, Notify, UpdateType}, auth::Headers, db::DbConn, error::Error, util::get_reqwest_client, }; -#[put("/devices/identifier//clear-token")] -fn clear_device_token(uuid: String) -> &'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: String, 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 { @@ -154,7 +121,8 @@ async fn post_eq_domains( user.save(&mut conn).await?; - nt.send_user_update(UpdateType::SyncSettings, &user).await; + nt.send_user_update(UpdateType::SyncSettings as i32, &user).await; + push_user_update(UpdateType::SyncSettings as i32, &user).await; Ok(Json(json!({}))) } diff --git a/src/api/core/organizations.rs b/src/api/core/organizations.rs index 9c46617ab6..51de00d91a 100644 --- a/src/api/core/organizations.rs +++ b/src/api/core/organizations.rs @@ -6,8 +6,8 @@ use serde_json::Value; use crate::{ api::{ core::{log_event, CipherSyncData, CipherSyncType}, - ApiResult, EmptyResult, JsonResult, JsonUpcase, JsonUpcaseVec, JsonVec, Notify, NumberOrString, PasswordData, - UpdateType, + push_logout, push_user_update, ApiResult, EmptyResult, JsonResult, JsonUpcase, JsonUpcaseVec, JsonVec, Notify, + NumberOrString, PasswordData, UpdateType, }, auth::{decode_invite, AdminHeaders, Headers, ManagerHeaders, ManagerHeadersLoose, OwnerHeaders}, db::{models::*, DbConn}, @@ -1209,7 +1209,8 @@ async fn _confirm_invite( let save_result = user_to_confirm.save(conn).await; if let Some(user) = User::find_by_uuid(&user_to_confirm.user_uuid, conn).await { - nt.send_user_update(UpdateType::SyncOrgKeys, &user).await; + nt.send_user_update(UpdateType::SyncOrgKeys as i32, &user).await; + push_user_update(UpdateType::SyncOrgKeys as i32, &user).await; } save_result @@ -1449,7 +1450,8 @@ async fn _delete_user( .await; if let Some(user) = User::find_by_uuid(&user_to_delete.user_uuid, conn).await { - nt.send_user_update(UpdateType::SyncOrgKeys, &user).await; + nt.send_user_update(UpdateType::SyncOrgKeys as i32, &user).await; + push_user_update(UpdateType::SyncOrgKeys as i32, &user).await; } user_to_delete.delete(conn).await @@ -2657,6 +2659,7 @@ async fn put_reset_password( user.save(&mut conn).await?; nt.send_logout(&user, None).await; + push_logout(&user, None, &mut conn).await; log_event( EventType::OrganizationUserAdminResetPassword as i32, diff --git a/src/api/core/sends.rs b/src/api/core/sends.rs index b086663ad2..b9d13c032b 100644 --- a/src/api/core/sends.rs +++ b/src/api/core/sends.rs @@ -8,7 +8,7 @@ use rocket::serde::json::Json; use serde_json::Value; use crate::{ - api::{ApiResult, EmptyResult, JsonResult, JsonUpcase, Notify, NumberOrString, UpdateType}, + api::{push_send_update, ApiResult, EmptyResult, JsonResult, JsonUpcase, Notify, NumberOrString, UpdateType}, auth::{ClientIp, Headers, Host}, db::{models::*, DbConn, DbPool}, util::SafeString, @@ -180,7 +180,8 @@ async fn post_send(data: JsonUpcase, headers: Headers, mut conn: DbCon let mut send = create_send(data, headers.user.uuid)?; send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendCreate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendCreate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendCreate as i32, &send).await; Ok(Json(send.to_json())) } @@ -252,7 +253,8 @@ async fn post_send_file(data: Form>, headers: Headers, mut conn: // Save the changes in the database send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendCreate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendCreate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendCreate as i32, &send).await; Ok(Json(send.to_json())) } @@ -335,7 +337,9 @@ async fn post_send_file_v2_data( data.data.move_copy_to(file_path).await? } - nt.send_send_update(UpdateType::SyncSendCreate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendCreate as i32, &send, &send.update_users_revision(&mut conn).await) + .await; + push_send_update(UpdateType::SyncSendCreate as i32, &send).await; } else { err!("Send not found. Unable to save the file."); } @@ -397,7 +401,8 @@ async fn post_access( send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendUpdate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendUpdate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendUpdate as i32, &send).await; Ok(Json(send.to_json_access(&mut conn).await)) } @@ -448,7 +453,8 @@ async fn post_access_file( send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendUpdate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendUpdate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendUpdate as i32, &send).await; let token_claims = crate::auth::generate_send_claims(&send_id, &file_id); let token = crate::auth::encode_jwt(&token_claims); @@ -530,7 +536,8 @@ async fn put_send( } send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendUpdate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendUpdate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendUpdate as i32, &send).await; Ok(Json(send.to_json())) } @@ -547,7 +554,8 @@ async fn delete_send(id: String, headers: Headers, mut conn: DbConn, nt: Notify< } send.delete(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendDelete, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendDelete as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendDelete as i32, &send).await; Ok(()) } @@ -567,7 +575,8 @@ async fn put_remove_password(id: String, headers: Headers, mut conn: DbConn, nt: send.set_password(None); send.save(&mut conn).await?; - nt.send_send_update(UpdateType::SyncSendUpdate, &send, &send.update_users_revision(&mut conn).await).await; + nt.send_send_update(UpdateType::SyncSendUpdate as i32, &send, &send.update_users_revision(&mut conn).await).await; + push_send_update(UpdateType::SyncSendUpdate as i32, &send).await; Ok(Json(send.to_json())) } diff --git a/src/api/identity.rs b/src/api/identity.rs index 5115a534b3..37abf89b5d 100644 --- a/src/api/identity.rs +++ b/src/api/identity.rs @@ -389,7 +389,7 @@ async fn get_device(data: &ConnectData, conn: &mut DbConn, user: &User) -> (Devi // On iOS, device_type sends "iOS", on others it sends a number // When unknown or unable to parse, return 14, which is 'Unknown Browser' let device_type = util::try_parse_string(data.device_type.as_ref()).unwrap_or(14); - let device_id = data.device_identifier.clone().expect("No device id provided"); + let device_id = data.device_identifier.clone().expect("No device uuid provided"); let device_name = data.device_name.clone().expect("No device name provided"); let mut new_device = false; 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 2c96f0e4f2..ffb0c698a9 100644 --- a/src/api/notifications.rs +++ b/src/api/notifications.rs @@ -135,7 +135,7 @@ impl WebSocketUsers { } // NOTE: The last modified date needs to be updated before calling these methods - pub async fn send_user_update(&self, ut: UpdateType, user: &User) { + pub async fn send_user_update(&self, ut: i32, user: &User) { let data = create_update( vec![("UserId".into(), user.uuid.clone().into()), ("Date".into(), serialize_date(user.updated_at))], ut, @@ -148,14 +148,14 @@ impl WebSocketUsers { pub async fn send_logout(&self, user: &User, acting_device_uuid: Option) { let data = create_update( vec![("UserId".into(), user.uuid.clone().into()), ("Date".into(), serialize_date(user.updated_at))], - UpdateType::LogOut, + UpdateType::LogOut as i32, acting_device_uuid, ); self.send_update(&user.uuid, &data).await; } - pub async fn send_folder_update(&self, ut: UpdateType, folder: &Folder, acting_device_uuid: &String) { + pub async fn send_folder_update(&self, ut: i32, folder: &Folder, acting_device_uuid: &String) { let data = create_update( vec![ ("Id".into(), folder.uuid.clone().into()), @@ -171,7 +171,7 @@ impl WebSocketUsers { pub async fn send_cipher_update( &self, - ut: UpdateType, + ut: i32, cipher: &Cipher, user_uuids: &[String], acting_device_uuid: &String, @@ -196,7 +196,7 @@ impl WebSocketUsers { } } - pub async fn send_send_update(&self, ut: UpdateType, send: &Send, user_uuids: &[String]) { + pub async fn send_send_update(&self, ut: i32, send: &Send, user_uuids: &[String]) { let user_uuid = convert_option(send.user_uuid.clone()); let data = create_update( @@ -230,7 +230,7 @@ impl WebSocketUsers { ] ] */ -fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_uuid: Option) -> Vec { +fn create_update(payload: Vec<(Value, Value)>, ut: i32, acting_device_uuid: Option) -> Vec { use rmpv::Value as V; let value = V::Array(vec![ @@ -240,7 +240,7 @@ fn create_update(payload: Vec<(Value, Value)>, ut: UpdateType, acting_device_uui "ReceiveMessage".into(), V::Array(vec![V::Map(vec![ ("ContextId".into(), acting_device_uuid.map(|v| v.into()).unwrap_or_else(|| V::Nil)), - ("Type".into(), (ut as i32).into()), + ("Type".into(), ut.into()), ("Payload".into(), payload.into()), ])]), ]); @@ -253,7 +253,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..7c60012c0e --- /dev/null +++ b/src/api/push.rs @@ -0,0 +1,287 @@ +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; // 1.3.1 +use std::time::{Duration, Instant}; + +#[derive(Deserialize, Debug)] +#[allow(non_snake_case)] +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() { + let _ = 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() { + let _ = 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: i32, 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.clone() { + 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, + "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.as_str(), &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: i32, user: &User) { + let data = json!({ + "userId": user.uuid, + "organizationId": (), + "deviceId": (), + "identifier": (), + "type": ut, + "payload": { + "UserId": user.uuid, + "Date": user.updated_at + } + }); + + send_to_push_relay(data).await; +} + +pub async fn push_folder_update(ut: i32, 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, + "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: i32, send: &Send) { + if send.user_uuid.is_none() { + return; + } + + let data = json!({ + "userId": send.user_uuid, + "organizationId": (), + "deviceId": (), + "identifier": (), + "type": ut, + "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() { + let _ = Ok::<(), ()>(()); + } + + 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/auth.rs b/src/auth.rs index e5779dd6ce..42bf039d56 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -388,7 +388,7 @@ impl<'r> FromRequest<'r> for Headers { let device = match Device::find_by_uuid_and_user(&device_uuid, &user_uuid, &mut conn).await { Some(device) => device, - None => err_handler!("Invalid device id"), + None => err_handler!("Invalid device uuid"), }; let user = match User::find_by_uuid(&user_uuid, &mut conn).await { diff --git a/src/config.rs b/src/config.rs index 6ed19a7981..e7babe49e6 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. diff --git a/src/db/models/device.rs b/src/db/models/device.rs index e47ccadcb8..42c41741e8 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 delete_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, diff --git a/src/main.rs b/src/main.rs index b85b890093..d6252755e4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -104,6 +104,7 @@ async fn main() -> Result<(), Error> { exit(1); }); check_web_vault(); + check_push_config(); create_dir(&CONFIG.icon_cache_folder(), "icon cache"); create_dir(&CONFIG.tmp_folder(), "tmp folder"); @@ -417,6 +418,22 @@ async fn check_data_folder() { } } +fn check_push_config() { + if CONFIG.push_enabled() + && (CONFIG.push_installation_id() == String::new() || CONFIG.push_installation_key() == String::new()) + { + error!( + "Misconfigured Push Notification service\n\ + ########################################################################################\n\ + # It looks like you enabled Push Notification feature, but you didn't configured the #\n\ + # value. Make sure the installation id and key from https://bitwarden.com/host are #\n\ + # added to your configuration. #\n\ + ########################################################################################\n" + ); + exit(1); + } +} + /// Detect when using Docker or Podman the DATA_FOLDER is either a bind-mount or a volume created manually. /// If not created manually, then the data will not be persistent. /// A none persistent volume in either Docker or Podman is represented by a 64 alphanumerical string.