ciphers.rs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. use std::collections::{HashMap, HashSet};
  2. use std::path::Path;
  3. use rocket::{http::ContentType, request::Form, Data, Route};
  4. use rocket_contrib::json::Json;
  5. use serde_json::Value;
  6. use data_encoding::HEXLOWER;
  7. use multipart::server::{save::SavedData, Multipart, SaveResult};
  8. use crate::{
  9. api::{self, EmptyResult, JsonResult, JsonUpcase, Notify, PasswordData, UpdateType},
  10. auth::Headers,
  11. crypto,
  12. db::{models::*, DbConn},
  13. CONFIG,
  14. };
  15. pub fn routes() -> Vec<Route> {
  16. routes![
  17. sync,
  18. get_ciphers,
  19. get_cipher,
  20. get_cipher_admin,
  21. get_cipher_details,
  22. post_ciphers,
  23. put_cipher_admin,
  24. post_ciphers_admin,
  25. post_ciphers_create,
  26. post_ciphers_import,
  27. post_attachment,
  28. post_attachment_admin,
  29. post_attachment_share,
  30. delete_attachment_post,
  31. delete_attachment_post_admin,
  32. delete_attachment,
  33. delete_attachment_admin,
  34. post_cipher_admin,
  35. post_cipher_share,
  36. put_cipher_share,
  37. put_cipher_share_seleted,
  38. post_cipher,
  39. put_cipher,
  40. delete_cipher_post,
  41. delete_cipher_post_admin,
  42. delete_cipher_put,
  43. delete_cipher_put_admin,
  44. delete_cipher,
  45. delete_cipher_admin,
  46. delete_cipher_selected,
  47. delete_cipher_selected_post,
  48. delete_cipher_selected_put,
  49. restore_cipher_put,
  50. restore_cipher_put_admin,
  51. restore_cipher_selected,
  52. delete_all,
  53. move_cipher_selected,
  54. move_cipher_selected_put,
  55. put_collections_update,
  56. post_collections_update,
  57. post_collections_admin,
  58. put_collections_admin,
  59. ]
  60. }
  61. #[derive(FromForm, Default)]
  62. struct SyncData {
  63. #[form(field = "excludeDomains")]
  64. exclude_domains: bool, // Default: 'false'
  65. }
  66. #[get("/sync?<data..>")]
  67. fn sync(data: Form<SyncData>, headers: Headers, conn: DbConn) -> JsonResult {
  68. let user_json = headers.user.to_json(&conn);
  69. let folders = Folder::find_by_user(&headers.user.uuid, &conn);
  70. let folders_json: Vec<Value> = folders.iter().map(Folder::to_json).collect();
  71. let collections = Collection::find_by_user_uuid(&headers.user.uuid, &conn);
  72. let collections_json: Vec<Value> = collections.iter().map(Collection::to_json).collect();
  73. let policies = OrgPolicy::find_by_user(&headers.user.uuid, &conn);
  74. let policies_json: Vec<Value> = policies.iter().map(OrgPolicy::to_json).collect();
  75. let ciphers = Cipher::find_by_user(&headers.user.uuid, &conn);
  76. let ciphers_json: Vec<Value> = ciphers
  77. .iter()
  78. .map(|c| c.to_json(&headers.host, &headers.user.uuid, &conn))
  79. .collect();
  80. let domains_json = if data.exclude_domains {
  81. Value::Null
  82. } else {
  83. api::core::_get_eq_domains(headers, true).unwrap().into_inner()
  84. };
  85. Ok(Json(json!({
  86. "Profile": user_json,
  87. "Folders": folders_json,
  88. "Collections": collections_json,
  89. "Policies": policies_json,
  90. "Ciphers": ciphers_json,
  91. "Domains": domains_json,
  92. "Object": "sync"
  93. })))
  94. }
  95. #[get("/ciphers")]
  96. fn get_ciphers(headers: Headers, conn: DbConn) -> JsonResult {
  97. let ciphers = Cipher::find_by_user(&headers.user.uuid, &conn);
  98. let ciphers_json: Vec<Value> = ciphers
  99. .iter()
  100. .map(|c| c.to_json(&headers.host, &headers.user.uuid, &conn))
  101. .collect();
  102. Ok(Json(json!({
  103. "Data": ciphers_json,
  104. "Object": "list",
  105. "ContinuationToken": null
  106. })))
  107. }
  108. #[get("/ciphers/<uuid>")]
  109. fn get_cipher(uuid: String, headers: Headers, conn: DbConn) -> JsonResult {
  110. let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  111. Some(cipher) => cipher,
  112. None => err!("Cipher doesn't exist"),
  113. };
  114. if !cipher.is_accessible_to_user(&headers.user.uuid, &conn) {
  115. err!("Cipher is not owned by user")
  116. }
  117. Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
  118. }
  119. #[get("/ciphers/<uuid>/admin")]
  120. fn get_cipher_admin(uuid: String, headers: Headers, conn: DbConn) -> JsonResult {
  121. // TODO: Implement this correctly
  122. get_cipher(uuid, headers, conn)
  123. }
  124. #[get("/ciphers/<uuid>/details")]
  125. fn get_cipher_details(uuid: String, headers: Headers, conn: DbConn) -> JsonResult {
  126. get_cipher(uuid, headers, conn)
  127. }
  128. #[derive(Deserialize, Debug)]
  129. #[allow(non_snake_case)]
  130. pub struct CipherData {
  131. // Id is optional as it is included only in bulk share
  132. pub Id: Option<String>,
  133. // Folder id is not included in import
  134. FolderId: Option<String>,
  135. // TODO: Some of these might appear all the time, no need for Option
  136. OrganizationId: Option<String>,
  137. /*
  138. Login = 1,
  139. SecureNote = 2,
  140. Card = 3,
  141. Identity = 4
  142. */
  143. pub Type: i32, // TODO: Change this to NumberOrString
  144. pub Name: String,
  145. Notes: Option<String>,
  146. Fields: Option<Value>,
  147. // Only one of these should exist, depending on type
  148. Login: Option<Value>,
  149. SecureNote: Option<Value>,
  150. Card: Option<Value>,
  151. Identity: Option<Value>,
  152. Favorite: Option<bool>,
  153. PasswordHistory: Option<Value>,
  154. // These are used during key rotation
  155. #[serde(rename = "Attachments")]
  156. _Attachments: Option<Value>, // Unused, contains map of {id: filename}
  157. Attachments2: Option<HashMap<String, Attachments2Data>>,
  158. }
  159. #[derive(Deserialize, Debug)]
  160. #[allow(non_snake_case)]
  161. pub struct Attachments2Data {
  162. FileName: String,
  163. Key: String,
  164. }
  165. #[post("/ciphers/admin", data = "<data>")]
  166. fn post_ciphers_admin(data: JsonUpcase<ShareCipherData>, headers: Headers, conn: DbConn, nt: Notify) -> JsonResult {
  167. let data: ShareCipherData = data.into_inner().data;
  168. let mut cipher = Cipher::new(data.Cipher.Type, data.Cipher.Name.clone());
  169. cipher.user_uuid = Some(headers.user.uuid.clone());
  170. cipher.save(&conn)?;
  171. share_cipher_by_uuid(&cipher.uuid, data, &headers, &conn, &nt)
  172. }
  173. #[post("/ciphers/create", data = "<data>")]
  174. fn post_ciphers_create(data: JsonUpcase<ShareCipherData>, headers: Headers, conn: DbConn, nt: Notify) -> JsonResult {
  175. post_ciphers_admin(data, headers, conn, nt)
  176. }
  177. #[post("/ciphers", data = "<data>")]
  178. fn post_ciphers(data: JsonUpcase<CipherData>, headers: Headers, conn: DbConn, nt: Notify) -> JsonResult {
  179. let data: CipherData = data.into_inner().data;
  180. let mut cipher = Cipher::new(data.Type, data.Name.clone());
  181. update_cipher_from_data(&mut cipher, data, &headers, false, &conn, &nt, UpdateType::CipherCreate)?;
  182. Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
  183. }
  184. pub fn update_cipher_from_data(
  185. cipher: &mut Cipher,
  186. data: CipherData,
  187. headers: &Headers,
  188. shared_to_collection: bool,
  189. conn: &DbConn,
  190. nt: &Notify,
  191. ut: UpdateType,
  192. ) -> EmptyResult {
  193. if cipher.organization_uuid.is_some() && cipher.organization_uuid != data.OrganizationId {
  194. err!("Organization mismatch. Please resync the client before updating the cipher")
  195. }
  196. if let Some(org_id) = data.OrganizationId {
  197. match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
  198. None => err!("You don't have permission to add item to organization"),
  199. Some(org_user) => {
  200. if shared_to_collection
  201. || org_user.has_full_access()
  202. || cipher.is_write_accessible_to_user(&headers.user.uuid, &conn)
  203. {
  204. cipher.organization_uuid = Some(org_id);
  205. cipher.user_uuid = None;
  206. } else {
  207. err!("You don't have permission to add cipher directly to organization")
  208. }
  209. }
  210. }
  211. } else {
  212. cipher.user_uuid = Some(headers.user.uuid.clone());
  213. }
  214. if let Some(ref folder_id) = data.FolderId {
  215. match Folder::find_by_uuid(folder_id, conn) {
  216. Some(folder) => {
  217. if folder.user_uuid != headers.user.uuid {
  218. err!("Folder is not owned by user")
  219. }
  220. }
  221. None => err!("Folder doesn't exist"),
  222. }
  223. }
  224. // Modify attachments name and keys when rotating
  225. if let Some(attachments) = data.Attachments2 {
  226. for (id, attachment) in attachments {
  227. let mut saved_att = match Attachment::find_by_id(&id, &conn) {
  228. Some(att) => att,
  229. None => err!("Attachment doesn't exist"),
  230. };
  231. if saved_att.cipher_uuid != cipher.uuid {
  232. // Warn and break here since cloning ciphers provides attachment data but will not be cloned.
  233. // If we error out here it will break the whole cloning and causes empty ciphers to appear.
  234. warn!("Attachment is not owned by the cipher");
  235. break;
  236. }
  237. saved_att.akey = Some(attachment.Key);
  238. saved_att.file_name = attachment.FileName;
  239. saved_att.save(&conn)?;
  240. }
  241. }
  242. let type_data_opt = match data.Type {
  243. 1 => data.Login,
  244. 2 => data.SecureNote,
  245. 3 => data.Card,
  246. 4 => data.Identity,
  247. _ => err!("Invalid type"),
  248. };
  249. let mut type_data = match type_data_opt {
  250. Some(data) => data,
  251. None => err!("Data missing"),
  252. };
  253. // TODO: ******* Backwards compat start **********
  254. // To remove backwards compatibility, just delete this code,
  255. // and remove the compat code from cipher::to_json
  256. type_data["Name"] = Value::String(data.Name.clone());
  257. type_data["Notes"] = data.Notes.clone().map(Value::String).unwrap_or(Value::Null);
  258. type_data["Fields"] = data.Fields.clone().unwrap_or(Value::Null);
  259. type_data["PasswordHistory"] = data.PasswordHistory.clone().unwrap_or(Value::Null);
  260. // TODO: ******* Backwards compat end **********
  261. cipher.name = data.Name;
  262. cipher.notes = data.Notes;
  263. cipher.fields = data.Fields.map(|f| f.to_string());
  264. cipher.data = type_data.to_string();
  265. cipher.password_history = data.PasswordHistory.map(|f| f.to_string());
  266. cipher.save(&conn)?;
  267. cipher.move_to_folder(data.FolderId, &headers.user.uuid, &conn)?;
  268. cipher.set_favorite(data.Favorite, &headers.user.uuid, &conn)?;
  269. if ut != UpdateType::None {
  270. nt.send_cipher_update(ut, &cipher, &cipher.update_users_revision(&conn));
  271. }
  272. Ok(())
  273. }
  274. use super::folders::FolderData;
  275. #[derive(Deserialize)]
  276. #[allow(non_snake_case)]
  277. struct ImportData {
  278. Ciphers: Vec<CipherData>,
  279. Folders: Vec<FolderData>,
  280. FolderRelationships: Vec<RelationsData>,
  281. }
  282. #[derive(Deserialize)]
  283. #[allow(non_snake_case)]
  284. struct RelationsData {
  285. // Cipher id
  286. Key: usize,
  287. // Folder id
  288. Value: usize,
  289. }
  290. #[post("/ciphers/import", data = "<data>")]
  291. fn post_ciphers_import(data: JsonUpcase<ImportData>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  292. let data: ImportData = data.into_inner().data;
  293. // Read and create the folders
  294. let mut folders: Vec<_> = Vec::new();
  295. for folder in data.Folders.into_iter() {
  296. let mut new_folder = Folder::new(headers.user.uuid.clone(), folder.Name);
  297. new_folder.save(&conn)?;
  298. folders.push(new_folder);
  299. }
  300. // Read the relations between folders and ciphers
  301. let mut relations_map = HashMap::new();
  302. for relation in data.FolderRelationships {
  303. relations_map.insert(relation.Key, relation.Value);
  304. }
  305. // Read and create the ciphers
  306. for (index, mut cipher_data) in data.Ciphers.into_iter().enumerate() {
  307. let folder_uuid = relations_map.get(&index).map(|i| folders[*i].uuid.clone());
  308. cipher_data.FolderId = folder_uuid;
  309. let mut cipher = Cipher::new(cipher_data.Type, cipher_data.Name.clone());
  310. update_cipher_from_data(&mut cipher, cipher_data, &headers, false, &conn, &nt, UpdateType::None)?;
  311. }
  312. let mut user = headers.user;
  313. user.update_revision(&conn)?;
  314. nt.send_user_update(UpdateType::Vault, &user);
  315. Ok(())
  316. }
  317. #[put("/ciphers/<uuid>/admin", data = "<data>")]
  318. fn put_cipher_admin(
  319. uuid: String,
  320. data: JsonUpcase<CipherData>,
  321. headers: Headers,
  322. conn: DbConn,
  323. nt: Notify,
  324. ) -> JsonResult {
  325. put_cipher(uuid, data, headers, conn, nt)
  326. }
  327. #[post("/ciphers/<uuid>/admin", data = "<data>")]
  328. fn post_cipher_admin(
  329. uuid: String,
  330. data: JsonUpcase<CipherData>,
  331. headers: Headers,
  332. conn: DbConn,
  333. nt: Notify,
  334. ) -> JsonResult {
  335. post_cipher(uuid, data, headers, conn, nt)
  336. }
  337. #[post("/ciphers/<uuid>", data = "<data>")]
  338. fn post_cipher(uuid: String, data: JsonUpcase<CipherData>, headers: Headers, conn: DbConn, nt: Notify) -> JsonResult {
  339. put_cipher(uuid, data, headers, conn, nt)
  340. }
  341. #[put("/ciphers/<uuid>", data = "<data>")]
  342. fn put_cipher(uuid: String, data: JsonUpcase<CipherData>, headers: Headers, conn: DbConn, nt: Notify) -> JsonResult {
  343. let data: CipherData = data.into_inner().data;
  344. let mut cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  345. Some(cipher) => cipher,
  346. None => err!("Cipher doesn't exist"),
  347. };
  348. // TODO: Check if only the folder ID or favorite status is being changed.
  349. // These are per-user properties that technically aren't part of the
  350. // cipher itself, so the user shouldn't need write access to change these.
  351. // Interestingly, upstream Bitwarden doesn't properly handle this either.
  352. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  353. err!("Cipher is not write accessible")
  354. }
  355. update_cipher_from_data(&mut cipher, data, &headers, false, &conn, &nt, UpdateType::CipherUpdate)?;
  356. Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
  357. }
  358. #[derive(Deserialize)]
  359. #[allow(non_snake_case)]
  360. struct CollectionsAdminData {
  361. CollectionIds: Vec<String>,
  362. }
  363. #[put("/ciphers/<uuid>/collections", data = "<data>")]
  364. fn put_collections_update(
  365. uuid: String,
  366. data: JsonUpcase<CollectionsAdminData>,
  367. headers: Headers,
  368. conn: DbConn,
  369. ) -> EmptyResult {
  370. post_collections_admin(uuid, data, headers, conn)
  371. }
  372. #[post("/ciphers/<uuid>/collections", data = "<data>")]
  373. fn post_collections_update(
  374. uuid: String,
  375. data: JsonUpcase<CollectionsAdminData>,
  376. headers: Headers,
  377. conn: DbConn,
  378. ) -> EmptyResult {
  379. post_collections_admin(uuid, data, headers, conn)
  380. }
  381. #[put("/ciphers/<uuid>/collections-admin", data = "<data>")]
  382. fn put_collections_admin(
  383. uuid: String,
  384. data: JsonUpcase<CollectionsAdminData>,
  385. headers: Headers,
  386. conn: DbConn,
  387. ) -> EmptyResult {
  388. post_collections_admin(uuid, data, headers, conn)
  389. }
  390. #[post("/ciphers/<uuid>/collections-admin", data = "<data>")]
  391. fn post_collections_admin(
  392. uuid: String,
  393. data: JsonUpcase<CollectionsAdminData>,
  394. headers: Headers,
  395. conn: DbConn,
  396. ) -> EmptyResult {
  397. let data: CollectionsAdminData = data.into_inner().data;
  398. let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  399. Some(cipher) => cipher,
  400. None => err!("Cipher doesn't exist"),
  401. };
  402. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  403. err!("Cipher is not write accessible")
  404. }
  405. let posted_collections: HashSet<String> = data.CollectionIds.iter().cloned().collect();
  406. let current_collections: HashSet<String> = cipher
  407. .get_collections(&headers.user.uuid, &conn)
  408. .iter()
  409. .cloned()
  410. .collect();
  411. for collection in posted_collections.symmetric_difference(&current_collections) {
  412. match Collection::find_by_uuid(&collection, &conn) {
  413. None => err!("Invalid collection ID provided"),
  414. Some(collection) => {
  415. if collection.is_writable_by_user(&headers.user.uuid, &conn) {
  416. if posted_collections.contains(&collection.uuid) {
  417. // Add to collection
  418. CollectionCipher::save(&cipher.uuid, &collection.uuid, &conn)?;
  419. } else {
  420. // Remove from collection
  421. CollectionCipher::delete(&cipher.uuid, &collection.uuid, &conn)?;
  422. }
  423. } else {
  424. err!("No rights to modify the collection")
  425. }
  426. }
  427. }
  428. }
  429. Ok(())
  430. }
  431. #[derive(Deserialize)]
  432. #[allow(non_snake_case)]
  433. struct ShareCipherData {
  434. Cipher: CipherData,
  435. CollectionIds: Vec<String>,
  436. }
  437. #[post("/ciphers/<uuid>/share", data = "<data>")]
  438. fn post_cipher_share(
  439. uuid: String,
  440. data: JsonUpcase<ShareCipherData>,
  441. headers: Headers,
  442. conn: DbConn,
  443. nt: Notify,
  444. ) -> JsonResult {
  445. let data: ShareCipherData = data.into_inner().data;
  446. share_cipher_by_uuid(&uuid, data, &headers, &conn, &nt)
  447. }
  448. #[put("/ciphers/<uuid>/share", data = "<data>")]
  449. fn put_cipher_share(
  450. uuid: String,
  451. data: JsonUpcase<ShareCipherData>,
  452. headers: Headers,
  453. conn: DbConn,
  454. nt: Notify,
  455. ) -> JsonResult {
  456. let data: ShareCipherData = data.into_inner().data;
  457. share_cipher_by_uuid(&uuid, data, &headers, &conn, &nt)
  458. }
  459. #[derive(Deserialize)]
  460. #[allow(non_snake_case)]
  461. struct ShareSelectedCipherData {
  462. Ciphers: Vec<CipherData>,
  463. CollectionIds: Vec<String>,
  464. }
  465. #[put("/ciphers/share", data = "<data>")]
  466. fn put_cipher_share_seleted(
  467. data: JsonUpcase<ShareSelectedCipherData>,
  468. headers: Headers,
  469. conn: DbConn,
  470. nt: Notify,
  471. ) -> EmptyResult {
  472. let mut data: ShareSelectedCipherData = data.into_inner().data;
  473. let mut cipher_ids: Vec<String> = Vec::new();
  474. if data.Ciphers.is_empty() {
  475. err!("You must select at least one cipher.")
  476. }
  477. if data.CollectionIds.is_empty() {
  478. err!("You must select at least one collection.")
  479. }
  480. for cipher in data.Ciphers.iter() {
  481. match cipher.Id {
  482. Some(ref id) => cipher_ids.push(id.to_string()),
  483. None => err!("Request missing ids field"),
  484. };
  485. }
  486. let attachments = Attachment::find_by_ciphers(cipher_ids, &conn);
  487. if !attachments.is_empty() {
  488. err!("Ciphers should not have any attachments.")
  489. }
  490. while let Some(cipher) = data.Ciphers.pop() {
  491. let mut shared_cipher_data = ShareCipherData {
  492. Cipher: cipher,
  493. CollectionIds: data.CollectionIds.clone(),
  494. };
  495. match shared_cipher_data.Cipher.Id.take() {
  496. Some(id) => share_cipher_by_uuid(&id, shared_cipher_data, &headers, &conn, &nt)?,
  497. None => err!("Request missing ids field"),
  498. };
  499. }
  500. Ok(())
  501. }
  502. fn share_cipher_by_uuid(
  503. uuid: &str,
  504. data: ShareCipherData,
  505. headers: &Headers,
  506. conn: &DbConn,
  507. nt: &Notify,
  508. ) -> JsonResult {
  509. let mut cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  510. Some(cipher) => {
  511. if cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  512. cipher
  513. } else {
  514. err!("Cipher is not write accessible")
  515. }
  516. }
  517. None => err!("Cipher doesn't exist"),
  518. };
  519. let mut shared_to_collection = false;
  520. match data.Cipher.OrganizationId.clone() {
  521. // If we don't get an organization ID, we don't do anything
  522. // No error because this is used when using the Clone functionality
  523. None => {}
  524. Some(organization_uuid) => {
  525. for uuid in &data.CollectionIds {
  526. match Collection::find_by_uuid_and_org(uuid, &organization_uuid, &conn) {
  527. None => err!("Invalid collection ID provided"),
  528. Some(collection) => {
  529. if collection.is_writable_by_user(&headers.user.uuid, &conn) {
  530. CollectionCipher::save(&cipher.uuid, &collection.uuid, &conn)?;
  531. shared_to_collection = true;
  532. } else {
  533. err!("No rights to modify the collection")
  534. }
  535. }
  536. }
  537. }
  538. }
  539. };
  540. update_cipher_from_data(
  541. &mut cipher,
  542. data.Cipher,
  543. &headers,
  544. shared_to_collection,
  545. &conn,
  546. &nt,
  547. UpdateType::CipherUpdate,
  548. )?;
  549. Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
  550. }
  551. #[post("/ciphers/<uuid>/attachment", format = "multipart/form-data", data = "<data>")]
  552. fn post_attachment(
  553. uuid: String,
  554. data: Data,
  555. content_type: &ContentType,
  556. headers: Headers,
  557. conn: DbConn,
  558. nt: Notify,
  559. ) -> JsonResult {
  560. let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  561. Some(cipher) => cipher,
  562. None => err_discard!("Cipher doesn't exist", data),
  563. };
  564. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  565. err_discard!("Cipher is not write accessible", data)
  566. }
  567. let mut params = content_type.params();
  568. let boundary_pair = params.next().expect("No boundary provided");
  569. let boundary = boundary_pair.1;
  570. let size_limit = if let Some(ref user_uuid) = cipher.user_uuid {
  571. match CONFIG.user_attachment_limit() {
  572. Some(0) => err_discard!("Attachments are disabled", data),
  573. Some(limit_kb) => {
  574. let left = (limit_kb * 1024) - Attachment::size_by_user(user_uuid, &conn);
  575. if left <= 0 {
  576. err_discard!("Attachment size limit reached! Delete some files to open space", data)
  577. }
  578. Some(left as u64)
  579. }
  580. None => None,
  581. }
  582. } else if let Some(ref org_uuid) = cipher.organization_uuid {
  583. match CONFIG.org_attachment_limit() {
  584. Some(0) => err_discard!("Attachments are disabled", data),
  585. Some(limit_kb) => {
  586. let left = (limit_kb * 1024) - Attachment::size_by_org(org_uuid, &conn);
  587. if left <= 0 {
  588. err_discard!("Attachment size limit reached! Delete some files to open space", data)
  589. }
  590. Some(left as u64)
  591. }
  592. None => None,
  593. }
  594. } else {
  595. err_discard!("Cipher is neither owned by a user nor an organization", data);
  596. };
  597. let base_path = Path::new(&CONFIG.attachments_folder()).join(&cipher.uuid);
  598. let mut attachment_key = None;
  599. let mut error = None;
  600. Multipart::with_body(data.open(), boundary)
  601. .foreach_entry(|mut field| {
  602. match &*field.headers.name {
  603. "key" => {
  604. use std::io::Read;
  605. let mut key_buffer = String::new();
  606. if field.data.read_to_string(&mut key_buffer).is_ok() {
  607. attachment_key = Some(key_buffer);
  608. }
  609. }
  610. "data" => {
  611. // This is provided by the client, don't trust it
  612. let name = field.headers.filename.expect("No filename provided");
  613. let file_name = HEXLOWER.encode(&crypto::get_random(vec![0; 10]));
  614. let path = base_path.join(&file_name);
  615. let size = match field.data.save().memory_threshold(0).size_limit(size_limit).with_path(path.clone()) {
  616. SaveResult::Full(SavedData::File(_, size)) => size as i32,
  617. SaveResult::Full(other) => {
  618. std::fs::remove_file(path).ok();
  619. error = Some(format!("Attachment is not a file: {:?}", other));
  620. return;
  621. }
  622. SaveResult::Partial(_, reason) => {
  623. std::fs::remove_file(path).ok();
  624. error = Some(format!("Attachment size limit exceeded with this file: {:?}", reason));
  625. return;
  626. }
  627. SaveResult::Error(e) => {
  628. std::fs::remove_file(path).ok();
  629. error = Some(format!("Error: {:?}", e));
  630. return;
  631. }
  632. };
  633. let mut attachment = Attachment::new(file_name, cipher.uuid.clone(), name, size);
  634. attachment.akey = attachment_key.clone();
  635. attachment.save(&conn).expect("Error saving attachment");
  636. }
  637. _ => error!("Invalid multipart name"),
  638. }
  639. })
  640. .expect("Error processing multipart data");
  641. if let Some(ref e) = error {
  642. err!(e);
  643. }
  644. nt.send_cipher_update(UpdateType::CipherUpdate, &cipher, &cipher.update_users_revision(&conn));
  645. Ok(Json(cipher.to_json(&headers.host, &headers.user.uuid, &conn)))
  646. }
  647. #[post("/ciphers/<uuid>/attachment-admin", format = "multipart/form-data", data = "<data>")]
  648. fn post_attachment_admin(
  649. uuid: String,
  650. data: Data,
  651. content_type: &ContentType,
  652. headers: Headers,
  653. conn: DbConn,
  654. nt: Notify,
  655. ) -> JsonResult {
  656. post_attachment(uuid, data, content_type, headers, conn, nt)
  657. }
  658. #[post("/ciphers/<uuid>/attachment/<attachment_id>/share", format = "multipart/form-data", data = "<data>")]
  659. fn post_attachment_share(
  660. uuid: String,
  661. attachment_id: String,
  662. data: Data,
  663. content_type: &ContentType,
  664. headers: Headers,
  665. conn: DbConn,
  666. nt: Notify,
  667. ) -> JsonResult {
  668. _delete_cipher_attachment_by_id(&uuid, &attachment_id, &headers, &conn, &nt)?;
  669. post_attachment(uuid, data, content_type, headers, conn, nt)
  670. }
  671. #[post("/ciphers/<uuid>/attachment/<attachment_id>/delete-admin")]
  672. fn delete_attachment_post_admin(
  673. uuid: String,
  674. attachment_id: String,
  675. headers: Headers,
  676. conn: DbConn,
  677. nt: Notify,
  678. ) -> EmptyResult {
  679. delete_attachment(uuid, attachment_id, headers, conn, nt)
  680. }
  681. #[post("/ciphers/<uuid>/attachment/<attachment_id>/delete")]
  682. fn delete_attachment_post(
  683. uuid: String,
  684. attachment_id: String,
  685. headers: Headers,
  686. conn: DbConn,
  687. nt: Notify,
  688. ) -> EmptyResult {
  689. delete_attachment(uuid, attachment_id, headers, conn, nt)
  690. }
  691. #[delete("/ciphers/<uuid>/attachment/<attachment_id>")]
  692. fn delete_attachment(uuid: String, attachment_id: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  693. _delete_cipher_attachment_by_id(&uuid, &attachment_id, &headers, &conn, &nt)
  694. }
  695. #[delete("/ciphers/<uuid>/attachment/<attachment_id>/admin")]
  696. fn delete_attachment_admin(
  697. uuid: String,
  698. attachment_id: String,
  699. headers: Headers,
  700. conn: DbConn,
  701. nt: Notify,
  702. ) -> EmptyResult {
  703. _delete_cipher_attachment_by_id(&uuid, &attachment_id, &headers, &conn, &nt)
  704. }
  705. #[post("/ciphers/<uuid>/delete")]
  706. fn delete_cipher_post(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  707. _delete_cipher_by_uuid(&uuid, &headers, &conn, false, &nt)
  708. }
  709. #[post("/ciphers/<uuid>/delete-admin")]
  710. fn delete_cipher_post_admin(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  711. _delete_cipher_by_uuid(&uuid, &headers, &conn, false, &nt)
  712. }
  713. #[put("/ciphers/<uuid>/delete")]
  714. fn delete_cipher_put(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  715. _delete_cipher_by_uuid(&uuid, &headers, &conn, true, &nt)
  716. }
  717. #[put("/ciphers/<uuid>/delete-admin")]
  718. fn delete_cipher_put_admin(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  719. _delete_cipher_by_uuid(&uuid, &headers, &conn, true, &nt)
  720. }
  721. #[delete("/ciphers/<uuid>")]
  722. fn delete_cipher(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  723. _delete_cipher_by_uuid(&uuid, &headers, &conn, false, &nt)
  724. }
  725. #[delete("/ciphers/<uuid>/admin")]
  726. fn delete_cipher_admin(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  727. _delete_cipher_by_uuid(&uuid, &headers, &conn, false, &nt)
  728. }
  729. #[delete("/ciphers", data = "<data>")]
  730. fn delete_cipher_selected(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  731. _delete_multiple_ciphers(data, headers, conn, false, nt)
  732. }
  733. #[post("/ciphers/delete", data = "<data>")]
  734. fn delete_cipher_selected_post(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  735. _delete_multiple_ciphers(data, headers, conn, false, nt)
  736. }
  737. #[put("/ciphers/delete", data = "<data>")]
  738. fn delete_cipher_selected_put(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  739. _delete_multiple_ciphers(data, headers, conn, true, nt)
  740. }
  741. #[put("/ciphers/<uuid>/restore")]
  742. fn restore_cipher_put(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  743. _restore_cipher_by_uuid(&uuid, &headers, &conn, &nt)
  744. }
  745. #[put("/ciphers/<uuid>/restore-admin")]
  746. fn restore_cipher_put_admin(uuid: String, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  747. _restore_cipher_by_uuid(&uuid, &headers, &conn, &nt)
  748. }
  749. #[put("/ciphers/restore", data = "<data>")]
  750. fn restore_cipher_selected(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  751. _restore_multiple_ciphers(data, headers, conn, nt)
  752. }
  753. #[derive(Deserialize)]
  754. #[allow(non_snake_case)]
  755. struct MoveCipherData {
  756. FolderId: Option<String>,
  757. Ids: Vec<String>,
  758. }
  759. #[post("/ciphers/move", data = "<data>")]
  760. fn move_cipher_selected(data: JsonUpcase<MoveCipherData>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  761. let data = data.into_inner().data;
  762. let user_uuid = headers.user.uuid;
  763. if let Some(ref folder_id) = data.FolderId {
  764. match Folder::find_by_uuid(folder_id, &conn) {
  765. Some(folder) => {
  766. if folder.user_uuid != user_uuid {
  767. err!("Folder is not owned by user")
  768. }
  769. }
  770. None => err!("Folder doesn't exist"),
  771. }
  772. }
  773. for uuid in data.Ids {
  774. let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  775. Some(cipher) => cipher,
  776. None => err!("Cipher doesn't exist"),
  777. };
  778. if !cipher.is_accessible_to_user(&user_uuid, &conn) {
  779. err!("Cipher is not accessible by user")
  780. }
  781. // Move cipher
  782. cipher.move_to_folder(data.FolderId.clone(), &user_uuid, &conn)?;
  783. nt.send_cipher_update(UpdateType::CipherUpdate, &cipher, &[user_uuid.clone()]);
  784. }
  785. Ok(())
  786. }
  787. #[put("/ciphers/move", data = "<data>")]
  788. fn move_cipher_selected_put(
  789. data: JsonUpcase<MoveCipherData>,
  790. headers: Headers,
  791. conn: DbConn,
  792. nt: Notify,
  793. ) -> EmptyResult {
  794. move_cipher_selected(data, headers, conn, nt)
  795. }
  796. #[derive(FromForm)]
  797. struct OrganizationId {
  798. #[form(field = "organizationId")]
  799. org_id: String,
  800. }
  801. #[post("/ciphers/purge?<organization..>", data = "<data>")]
  802. fn delete_all(
  803. organization: Option<Form<OrganizationId>>,
  804. data: JsonUpcase<PasswordData>,
  805. headers: Headers,
  806. conn: DbConn,
  807. nt: Notify,
  808. ) -> EmptyResult {
  809. let data: PasswordData = data.into_inner().data;
  810. let password_hash = data.MasterPasswordHash;
  811. let mut user = headers.user;
  812. if !user.check_valid_password(&password_hash) {
  813. err!("Invalid password")
  814. }
  815. match organization {
  816. Some(org_data) => {
  817. // Organization ID in query params, purging organization vault
  818. match UserOrganization::find_by_user_and_org(&user.uuid, &org_data.org_id, &conn) {
  819. None => err!("You don't have permission to purge the organization vault"),
  820. Some(user_org) => {
  821. if user_org.atype == UserOrgType::Owner {
  822. Cipher::delete_all_by_organization(&org_data.org_id, &conn)?;
  823. Collection::delete_all_by_organization(&org_data.org_id, &conn)?;
  824. nt.send_user_update(UpdateType::Vault, &user);
  825. Ok(())
  826. } else {
  827. err!("You don't have permission to purge the organization vault");
  828. }
  829. }
  830. }
  831. }
  832. None => {
  833. // No organization ID in query params, purging user vault
  834. // Delete ciphers and their attachments
  835. for cipher in Cipher::find_owned_by_user(&user.uuid, &conn) {
  836. cipher.delete(&conn)?;
  837. }
  838. // Delete folders
  839. for f in Folder::find_by_user(&user.uuid, &conn) {
  840. f.delete(&conn)?;
  841. }
  842. user.update_revision(&conn)?;
  843. nt.send_user_update(UpdateType::Vault, &user);
  844. Ok(())
  845. }
  846. }
  847. }
  848. fn _delete_cipher_by_uuid(uuid: &str, headers: &Headers, conn: &DbConn, soft_delete: bool, nt: &Notify) -> EmptyResult {
  849. let mut cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  850. Some(cipher) => cipher,
  851. None => err!("Cipher doesn't exist"),
  852. };
  853. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  854. err!("Cipher can't be deleted by user")
  855. }
  856. if soft_delete {
  857. cipher.deleted_at = Some(chrono::Utc::now().naive_utc());
  858. cipher.save(&conn)?;
  859. nt.send_cipher_update(UpdateType::CipherUpdate, &cipher, &cipher.update_users_revision(&conn));
  860. } else {
  861. cipher.delete(&conn)?;
  862. nt.send_cipher_update(UpdateType::CipherDelete, &cipher, &cipher.update_users_revision(&conn));
  863. }
  864. Ok(())
  865. }
  866. fn _delete_multiple_ciphers(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, soft_delete: bool, nt: Notify) -> EmptyResult {
  867. let data: Value = data.into_inner().data;
  868. let uuids = match data.get("Ids") {
  869. Some(ids) => match ids.as_array() {
  870. Some(ids) => ids.iter().filter_map(Value::as_str),
  871. None => err!("Posted ids field is not an array"),
  872. },
  873. None => err!("Request missing ids field"),
  874. };
  875. for uuid in uuids {
  876. if let error @ Err(_) = _delete_cipher_by_uuid(uuid, &headers, &conn, soft_delete, &nt) {
  877. return error;
  878. };
  879. }
  880. Ok(())
  881. }
  882. fn _restore_cipher_by_uuid(uuid: &str, headers: &Headers, conn: &DbConn, nt: &Notify) -> EmptyResult {
  883. let mut cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  884. Some(cipher) => cipher,
  885. None => err!("Cipher doesn't exist"),
  886. };
  887. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  888. err!("Cipher can't be restored by user")
  889. }
  890. cipher.deleted_at = None;
  891. cipher.save(&conn)?;
  892. nt.send_cipher_update(UpdateType::CipherUpdate, &cipher, &cipher.update_users_revision(&conn));
  893. Ok(())
  894. }
  895. fn _restore_multiple_ciphers(data: JsonUpcase<Value>, headers: Headers, conn: DbConn, nt: Notify) -> EmptyResult {
  896. let data: Value = data.into_inner().data;
  897. let uuids = match data.get("Ids") {
  898. Some(ids) => match ids.as_array() {
  899. Some(ids) => ids.iter().filter_map(Value::as_str),
  900. None => err!("Posted ids field is not an array"),
  901. },
  902. None => err!("Request missing ids field"),
  903. };
  904. for uuid in uuids {
  905. if let error @ Err(_) = _restore_cipher_by_uuid(uuid, &headers, &conn, &nt) {
  906. return error;
  907. };
  908. }
  909. Ok(())
  910. }
  911. fn _delete_cipher_attachment_by_id(
  912. uuid: &str,
  913. attachment_id: &str,
  914. headers: &Headers,
  915. conn: &DbConn,
  916. nt: &Notify,
  917. ) -> EmptyResult {
  918. let attachment = match Attachment::find_by_id(&attachment_id, &conn) {
  919. Some(attachment) => attachment,
  920. None => err!("Attachment doesn't exist"),
  921. };
  922. if attachment.cipher_uuid != uuid {
  923. err!("Attachment from other cipher")
  924. }
  925. let cipher = match Cipher::find_by_uuid(&uuid, &conn) {
  926. Some(cipher) => cipher,
  927. None => err!("Cipher doesn't exist"),
  928. };
  929. if !cipher.is_write_accessible_to_user(&headers.user.uuid, &conn) {
  930. err!("Cipher cannot be deleted by user")
  931. }
  932. // Delete attachment
  933. attachment.delete(&conn)?;
  934. nt.send_cipher_update(UpdateType::CipherUpdate, &cipher, &cipher.update_users_revision(&conn));
  935. Ok(())
  936. }