ciphers.rs 28 KB

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