util.rs 5.0 KB

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