util.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{
  19. collections::HashMap,
  20. fs::{create_dir_all, read_dir},
  21. path::{Path, PathBuf},
  22. };
  23. use darkfi_serial::{deserialize, serialize};
  24. use dryoc::{
  25. classic::crypto_secretbox::{crypto_secretbox_easy, crypto_secretbox_open_easy, Key, Nonce},
  26. constants::CRYPTO_SECRETBOX_MACBYTES,
  27. dryocbox::NewByteArray,
  28. };
  29. use log::{error, info, warn};
  30. use unicode_segmentation::UnicodeSegmentation;
  31. use darkfi::{util::path::expand_path, Error, Result};
  32. use crate::{Args, EncryptedPatch, Patch};
  33. /// Split a `&str` into a vector of each of its chars.
  34. pub fn str_to_chars(s: &str) -> Vec<&str> {
  35. s.graphemes(true).collect::<Vec<&str>>()
  36. }
  37. /// Parse a base58 string for a `crypto_secretbox` secret.
  38. fn parse_b58_secret(s: &str) -> Result<[u8; 32]> {
  39. match bs58::decode(s).into_vec() {
  40. Ok(v) => {
  41. if v.len() != 32 {
  42. return Err(Error::Custom("Secret is not 32 bytes long".to_string()))
  43. }
  44. Ok(v.try_into().unwrap())
  45. }
  46. Err(e) => Err(Error::Custom(format!("Unable to parse secret from base58: {}", e))),
  47. }
  48. }
  49. /// Parse a TOML string for configured workspaces and return an `HashMap`
  50. /// of parsed data. Does not error on failures, just warns if something is
  51. /// misconfigured.
  52. pub fn parse_workspaces(toml_str: &str) -> HashMap<String, Key> {
  53. let mut ret = HashMap::new();
  54. let settings: Args = match toml::from_str(toml_str) {
  55. Ok(v) => v,
  56. Err(e) => {
  57. error!("Failed parsing TOML from string: {}", e);
  58. return ret
  59. }
  60. };
  61. for workspace in settings.workspace {
  62. let wrk: Vec<&str> = workspace.split(':').collect();
  63. if wrk.len() != 2 {
  64. warn!("Invalid workspace: {}", workspace);
  65. continue
  66. }
  67. let secret = match parse_b58_secret(wrk[1]) {
  68. Ok(v) => v,
  69. Err(e) => {
  70. warn!("Failed parsing secret for workspace {}: {}", wrk[0], e);
  71. continue
  72. }
  73. };
  74. let docs_path = match expand_path(&settings.docs) {
  75. Ok(v) => v,
  76. Err(e) => {
  77. warn!("Failed expanding docs path for workspace {}: {}", wrk[0], e);
  78. continue
  79. }
  80. };
  81. if let Err(e) = create_dir_all(docs_path.join(wrk[0])) {
  82. warn!("Failed creating directory for workspace {}: {}", wrk[0], e);
  83. continue
  84. }
  85. info!("Added parsed workspace: {}", wrk[0]);
  86. ret.insert(wrk[0].to_string(), secret);
  87. }
  88. ret
  89. }
  90. /// Encrypt a patch using a NaCl crypto_secretbox given a `Patch` and a `Key`.
  91. pub fn encrypt_patch(patch: &Patch, key: &Key) -> Result<EncryptedPatch> {
  92. let nonce = Nonce::gen();
  93. let payload = serialize(patch);
  94. let mut ciphertext = vec![0u8; payload.len() + CRYPTO_SECRETBOX_MACBYTES];
  95. if let Err(e) = crypto_secretbox_easy(&mut ciphertext, &payload, &nonce, key) {
  96. error!("encrypt_patch: Failed encrypting patch: {}", e);
  97. return Err(Error::Custom(format!("Failed encrypting darkwiki patch: {}", e)))
  98. }
  99. Ok(EncryptedPatch { nonce, ciphertext })
  100. }
  101. /// Decrypt a patch using a NaCl crypto_secretbox given an `EncryptedPatch` and a `Key`.
  102. pub fn decrypt_patch(patch: &EncryptedPatch, key: &Key) -> Result<Patch> {
  103. let nonce = &patch.nonce;
  104. let ciphertext = &patch.ciphertext;
  105. let mut decrypted = vec![0u8; ciphertext.len() - CRYPTO_SECRETBOX_MACBYTES];
  106. if let Err(e) = crypto_secretbox_open_easy(&mut decrypted, ciphertext, nonce, key) {
  107. error!("decrypt_patch: Failed decrypting patch: {}", e);
  108. return Err(Error::Custom(format!("Failed decrypting darkwiki patch: {}", e)))
  109. }
  110. Ok(deserialize(&decrypted)?)
  111. }
  112. /// TODO: DOCUMENT ME
  113. /// FIXME: There's checking of file extensions here. Take care that the rest of the code
  114. /// is robust against this attack.
  115. pub fn get_docs_paths(files: &mut Vec<PathBuf>, path: &Path, parent: Option<&Path>) -> Result<()> {
  116. let docs = read_dir(path)?;
  117. let docs = docs.filter(|d| d.is_ok()).map(|d| d.unwrap().path()).collect::<Vec<PathBuf>>();
  118. for doc in docs {
  119. if let Some(f) = doc.file_name() {
  120. let filename = PathBuf::from(f);
  121. let filename = if let Some(parent) = parent { parent.join(filename) } else { filename };
  122. if doc.is_file() {
  123. if let Some(ext) = doc.extension() {
  124. if ext == "md" || ext == "markdown" {
  125. files.push(filename);
  126. }
  127. }
  128. } else if doc.is_dir() {
  129. if f == ".log" {
  130. continue
  131. }
  132. get_docs_paths(files, &doc, Some(&filename))?;
  133. }
  134. }
  135. }
  136. Ok(())
  137. }
  138. /// Hash a path and workspace, and encode with base58, providing an ID.
  139. pub fn path_to_id(path: &str, workspace: &str) -> String {
  140. let mut hasher = blake3::Hasher::new();
  141. hasher.update(path.as_bytes());
  142. hasher.update(workspace.as_bytes());
  143. bs58::encode(hasher.finalize().as_bytes()).into_string()
  144. }