util.rs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. use std::{
  2. fs::{create_dir_all, read_dir},
  3. path::{Path, PathBuf},
  4. };
  5. use darkfi_serial::{deserialize, serialize};
  6. use dryoc::{
  7. classic::crypto_secretbox::{crypto_secretbox_easy, crypto_secretbox_open_easy, Key, Nonce},
  8. constants::CRYPTO_SECRETBOX_MACBYTES,
  9. dryocbox::NewByteArray,
  10. };
  11. use fxhash::FxHashMap;
  12. use log::{error, info, warn};
  13. use unicode_segmentation::UnicodeSegmentation;
  14. use darkfi::{util::path::expand_path, Error, Result};
  15. use crate::{Args, EncryptedPatch, Patch};
  16. /// Split a `&str` into a vector of each of its chars.
  17. pub fn str_to_chars(s: &str) -> Vec<&str> {
  18. s.graphemes(true).collect::<Vec<&str>>()
  19. }
  20. /// Parse a base58 string for a `crypto_secretbox` secret.
  21. fn parse_b58_secret(s: &str) -> Result<[u8; 32]> {
  22. match bs58::decode(s).into_vec() {
  23. Ok(v) => {
  24. if v.len() != 32 {
  25. return Err(Error::Custom("Secret is not 32 bytes long".to_string()))
  26. }
  27. Ok(v.try_into().unwrap())
  28. }
  29. Err(e) => Err(Error::Custom(format!("Unable to parse secret from base58: {}", e))),
  30. }
  31. }
  32. /// Parse a TOML string for configured workspaces and return an `FxHashMap`
  33. /// of parsed data. Does not error on failures, just warns if something is
  34. /// misconfigured.
  35. pub fn parse_workspaces(toml_str: &str) -> FxHashMap<String, Key> {
  36. let mut ret = FxHashMap::default();
  37. let settings: Args = match toml::from_str(toml_str) {
  38. Ok(v) => v,
  39. Err(e) => {
  40. error!("Failed parsing TOML from string: {}", e);
  41. return ret
  42. }
  43. };
  44. for workspace in settings.workspace {
  45. let wrk: Vec<&str> = workspace.split(':').collect();
  46. if wrk.len() != 2 {
  47. warn!("Invalid workspace: {}", workspace);
  48. continue
  49. }
  50. let secret = match parse_b58_secret(wrk[1]) {
  51. Ok(v) => v,
  52. Err(e) => {
  53. warn!("Failed parsing secret for workspace {}: {}", wrk[0], e);
  54. continue
  55. }
  56. };
  57. let docs_path = match expand_path(&settings.docs) {
  58. Ok(v) => v,
  59. Err(e) => {
  60. warn!("Failed expanding docs path for workspace {}: {}", wrk[0], e);
  61. continue
  62. }
  63. };
  64. if let Err(e) = create_dir_all(docs_path.join(wrk[0])) {
  65. warn!("Failed creating directory for workspace {}: {}", wrk[0], e);
  66. continue
  67. }
  68. info!("Added parsed workspace: {}", wrk[0]);
  69. ret.insert(wrk[0].to_string(), secret);
  70. }
  71. ret
  72. }
  73. /// Encrypt a patch using a NaCl crypto_secretbox given a `Patch` and a `Key`.
  74. pub fn encrypt_patch(patch: &Patch, key: &Key) -> Result<EncryptedPatch> {
  75. let nonce = Nonce::gen();
  76. let payload = serialize(patch);
  77. let mut ciphertext = vec![0u8; payload.len() + CRYPTO_SECRETBOX_MACBYTES];
  78. if let Err(e) = crypto_secretbox_easy(&mut ciphertext, &payload, &nonce, key) {
  79. error!("encrypt_patch: Failed encrypting patch: {}", e);
  80. return Err(Error::Custom(format!("Failed encrypting darkwiki patch: {}", e)))
  81. }
  82. Ok(EncryptedPatch { nonce, ciphertext })
  83. }
  84. /// Decrypt a patch using a NaCl crypto_secretbox given an `EncryptedPatch` and a `Key`.
  85. pub fn decrypt_patch(patch: &EncryptedPatch, key: &Key) -> Result<Patch> {
  86. let nonce = &patch.nonce;
  87. let ciphertext = &patch.ciphertext;
  88. let mut decrypted = vec![0u8; ciphertext.len() - CRYPTO_SECRETBOX_MACBYTES];
  89. if let Err(e) = crypto_secretbox_open_easy(&mut decrypted, ciphertext, nonce, key) {
  90. error!("decrypt_patch: Failed decrypting patch: {}", e);
  91. return Err(Error::Custom(format!("Failed decrypting darkwiki patch: {}", e)))
  92. }
  93. Ok(deserialize(&decrypted)?)
  94. }
  95. /// TODO: DOCUMENT ME
  96. /// FIXME: There's checking of file extensions here. Take care that the rest of the code
  97. /// is robust against this attack.
  98. pub fn get_docs_paths(files: &mut Vec<PathBuf>, path: &Path, parent: Option<&Path>) -> Result<()> {
  99. let docs = read_dir(&path)?;
  100. let docs = docs.filter(|d| d.is_ok()).map(|d| d.unwrap().path()).collect::<Vec<PathBuf>>();
  101. for doc in docs {
  102. if let Some(f) = doc.file_name() {
  103. let filename = PathBuf::from(f);
  104. let filename = if let Some(parent) = parent { parent.join(filename) } else { filename };
  105. if doc.is_file() {
  106. if let Some(ext) = doc.extension() {
  107. if ext == "md" || ext == "markdown" {
  108. files.push(filename);
  109. }
  110. }
  111. } else if doc.is_dir() {
  112. if f == ".log" {
  113. continue
  114. }
  115. get_docs_paths(files, &doc, Some(&filename))?;
  116. }
  117. }
  118. }
  119. Ok(())
  120. }
  121. /// Hash a path and workspace, and encode with base58, providing an ID.
  122. pub fn path_to_id(path: &str, workspace: &str) -> String {
  123. let mut hasher = blake3::Hasher::new();
  124. hasher.update(path.as_bytes());
  125. hasher.update(workspace.as_bytes());
  126. bs58::encode(hasher.finalize().as_bytes()).into_string()
  127. }