config.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. use anyhow::{anyhow, bail, Context, Result};
  2. use serde::{Deserialize, Serialize};
  3. use std::collections::HashMap;
  4. use std::path::Path;
  5. use tokio::fs;
  6. #[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq)]
  7. pub enum TransportType {
  8. #[serde(rename = "tcp")]
  9. Tcp,
  10. #[serde(rename = "tls")]
  11. Tls,
  12. #[serde(rename = "noise")]
  13. Noise,
  14. }
  15. impl Default for TransportType {
  16. fn default() -> TransportType {
  17. TransportType::Tcp
  18. }
  19. }
  20. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
  21. pub struct ClientServiceConfig {
  22. #[serde(rename = "type", default = "default_service_type")]
  23. pub service_type: ServiceType,
  24. #[serde(skip)]
  25. pub name: String,
  26. pub local_addr: String,
  27. pub token: Option<String>,
  28. }
  29. impl ClientServiceConfig {
  30. pub fn with_name(name: &str) -> ClientServiceConfig {
  31. ClientServiceConfig {
  32. name: name.to_string(),
  33. ..Default::default()
  34. }
  35. }
  36. }
  37. #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq)]
  38. pub enum ServiceType {
  39. #[serde(rename = "tcp")]
  40. Tcp,
  41. #[serde(rename = "udp")]
  42. Udp,
  43. }
  44. impl Default for ServiceType {
  45. fn default() -> Self {
  46. ServiceType::Tcp
  47. }
  48. }
  49. fn default_service_type() -> ServiceType {
  50. Default::default()
  51. }
  52. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
  53. pub struct ServerServiceConfig {
  54. #[serde(rename = "type", default = "default_service_type")]
  55. pub service_type: ServiceType,
  56. #[serde(skip)]
  57. pub name: String,
  58. pub bind_addr: String,
  59. pub token: Option<String>,
  60. }
  61. impl ServerServiceConfig {
  62. pub fn with_name(name: &str) -> ServerServiceConfig {
  63. ServerServiceConfig {
  64. name: name.to_string(),
  65. ..Default::default()
  66. }
  67. }
  68. }
  69. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
  70. pub struct TlsConfig {
  71. pub hostname: Option<String>,
  72. pub trusted_root: Option<String>,
  73. pub pkcs12: Option<String>,
  74. pub pkcs12_password: Option<String>,
  75. }
  76. fn default_noise_pattern() -> String {
  77. String::from("Noise_NK_25519_ChaChaPoly_BLAKE2s")
  78. }
  79. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
  80. pub struct NoiseConfig {
  81. #[serde(default = "default_noise_pattern")]
  82. pub pattern: String,
  83. pub local_private_key: Option<String>,
  84. pub remote_public_key: Option<String>,
  85. // TODO: Maybe psk can be added
  86. }
  87. #[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
  88. pub struct TransportConfig {
  89. #[serde(rename = "type")]
  90. pub transport_type: TransportType,
  91. pub tls: Option<TlsConfig>,
  92. pub noise: Option<NoiseConfig>,
  93. }
  94. fn default_transport() -> TransportConfig {
  95. Default::default()
  96. }
  97. #[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
  98. pub struct ClientConfig {
  99. pub remote_addr: String,
  100. pub default_token: Option<String>,
  101. pub services: HashMap<String, ClientServiceConfig>,
  102. #[serde(default = "default_transport")]
  103. pub transport: TransportConfig,
  104. }
  105. #[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone)]
  106. pub struct ServerConfig {
  107. pub bind_addr: String,
  108. pub default_token: Option<String>,
  109. pub services: HashMap<String, ServerServiceConfig>,
  110. #[serde(default = "default_transport")]
  111. pub transport: TransportConfig,
  112. }
  113. #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
  114. #[serde(deny_unknown_fields)]
  115. pub struct Config {
  116. pub server: Option<ServerConfig>,
  117. pub client: Option<ClientConfig>,
  118. }
  119. impl Config {
  120. fn from_str(s: &str) -> Result<Config> {
  121. let mut config: Config = toml::from_str(s).with_context(|| "Failed to parse the config")?;
  122. if let Some(server) = config.server.as_mut() {
  123. Config::validate_server_config(server)?;
  124. }
  125. if let Some(client) = config.client.as_mut() {
  126. Config::validate_client_config(client)?;
  127. }
  128. if config.server.is_none() && config.client.is_none() {
  129. Err(anyhow!("Neither of `[server]` or `[client]` is defined"))
  130. } else {
  131. Ok(config)
  132. }
  133. }
  134. fn validate_server_config(server: &mut ServerConfig) -> Result<()> {
  135. // Validate services
  136. for (name, s) in &mut server.services {
  137. s.name = name.clone();
  138. if s.token.is_none() {
  139. s.token = server.default_token.clone();
  140. if s.token.is_none() {
  141. bail!("The token of service {} is not set", name);
  142. }
  143. }
  144. }
  145. Config::validate_transport_config(&server.transport, true)?;
  146. Ok(())
  147. }
  148. fn validate_client_config(client: &mut ClientConfig) -> Result<()> {
  149. // Validate services
  150. for (name, s) in &mut client.services {
  151. s.name = name.clone();
  152. if s.token.is_none() {
  153. s.token = client.default_token.clone();
  154. if s.token.is_none() {
  155. bail!("The token of service {} is not set", name);
  156. }
  157. }
  158. }
  159. Config::validate_transport_config(&client.transport, false)?;
  160. Ok(())
  161. }
  162. fn validate_transport_config(config: &TransportConfig, is_server: bool) -> Result<()> {
  163. match config.transport_type {
  164. TransportType::Tcp => Ok(()),
  165. TransportType::Tls => {
  166. let tls_config = config
  167. .tls
  168. .as_ref()
  169. .ok_or(anyhow!("Missing TLS configuration"))?;
  170. if is_server {
  171. tls_config
  172. .pkcs12
  173. .as_ref()
  174. .and(tls_config.pkcs12_password.as_ref())
  175. .ok_or(anyhow!("Missing `pkcs12` or `pkcs12_password`"))?;
  176. } else {
  177. tls_config
  178. .trusted_root
  179. .as_ref()
  180. .ok_or(anyhow!("Missing `trusted_root`"))?;
  181. }
  182. Ok(())
  183. }
  184. TransportType::Noise => {
  185. // The check is done in transport
  186. Ok(())
  187. }
  188. }
  189. }
  190. pub async fn from_file(path: &Path) -> Result<Config> {
  191. let s: String = fs::read_to_string(path)
  192. .await
  193. .with_context(|| format!("Failed to read the config {:?}", path))?;
  194. Config::from_str(&s).with_context(|| {
  195. "Configuration is invalid. Please refer to the configuration specification."
  196. })
  197. }
  198. }
  199. #[cfg(test)]
  200. mod tests {
  201. use super::*;
  202. use std::{fs, path::PathBuf};
  203. use anyhow::Result;
  204. fn list_config_files<T: AsRef<Path>>(root: T) -> Result<Vec<PathBuf>> {
  205. let mut files = Vec::new();
  206. for entry in fs::read_dir(root)? {
  207. let entry = entry?;
  208. let path = entry.path();
  209. if path.is_file() {
  210. files.push(path);
  211. } else if path.is_dir() {
  212. files.append(&mut list_config_files(path)?);
  213. }
  214. }
  215. Ok(files)
  216. }
  217. fn get_all_example_config() -> Result<Vec<PathBuf>> {
  218. Ok(list_config_files("./examples")?
  219. .into_iter()
  220. .filter(|x| x.ends_with(".toml"))
  221. .collect())
  222. }
  223. #[test]
  224. fn test_example_config() -> Result<()> {
  225. let paths = get_all_example_config()?;
  226. for p in paths {
  227. let s = fs::read_to_string(p)?;
  228. Config::from_str(&s)?;
  229. }
  230. Ok(())
  231. }
  232. #[test]
  233. fn test_valid_config() -> Result<()> {
  234. let paths = list_config_files("tests/config_test/valid_config")?;
  235. for p in paths {
  236. let s = fs::read_to_string(p)?;
  237. Config::from_str(&s)?;
  238. }
  239. Ok(())
  240. }
  241. #[test]
  242. fn test_invalid_config() -> Result<()> {
  243. let paths = list_config_files("tests/config_test/invalid_config")?;
  244. for p in paths {
  245. let s = fs::read_to_string(p)?;
  246. assert!(Config::from_str(&s).is_err());
  247. }
  248. Ok(())
  249. }
  250. #[test]
  251. fn test_validate_server_config() -> Result<()> {
  252. let mut cfg = ServerConfig::default();
  253. cfg.services.insert(
  254. "foo1".into(),
  255. ServerServiceConfig {
  256. service_type: ServiceType::Tcp,
  257. name: "foo1".into(),
  258. bind_addr: "127.0.0.1:80".into(),
  259. token: None,
  260. },
  261. );
  262. // Missing the token
  263. assert!(Config::validate_server_config(&mut cfg).is_err());
  264. // Use the default token
  265. cfg.default_token = Some("123".into());
  266. assert!(Config::validate_server_config(&mut cfg).is_ok());
  267. assert_eq!(
  268. cfg.services
  269. .get("foo1")
  270. .as_ref()
  271. .unwrap()
  272. .token
  273. .as_ref()
  274. .unwrap(),
  275. "123"
  276. );
  277. // The default token won't override the service token
  278. cfg.services.get_mut("foo1").unwrap().token = Some("4".into());
  279. assert!(Config::validate_server_config(&mut cfg).is_ok());
  280. assert_eq!(
  281. cfg.services
  282. .get("foo1")
  283. .as_ref()
  284. .unwrap()
  285. .token
  286. .as_ref()
  287. .unwrap(),
  288. "4"
  289. );
  290. Ok(())
  291. }
  292. #[test]
  293. fn test_validate_client_config() -> Result<()> {
  294. let mut cfg = ClientConfig::default();
  295. cfg.services.insert(
  296. "foo1".into(),
  297. ClientServiceConfig {
  298. service_type: ServiceType::Tcp,
  299. name: "foo1".into(),
  300. local_addr: "127.0.0.1:80".into(),
  301. token: None,
  302. },
  303. );
  304. // Missing the token
  305. assert!(Config::validate_client_config(&mut cfg).is_err());
  306. // Use the default token
  307. cfg.default_token = Some("123".into());
  308. assert!(Config::validate_client_config(&mut cfg).is_ok());
  309. assert_eq!(
  310. cfg.services
  311. .get("foo1")
  312. .as_ref()
  313. .unwrap()
  314. .token
  315. .as_ref()
  316. .unwrap(),
  317. "123"
  318. );
  319. // The default token won't override the service token
  320. cfg.services.get_mut("foo1").unwrap().token = Some("4".into());
  321. assert!(Config::validate_client_config(&mut cfg).is_ok());
  322. assert_eq!(
  323. cfg.services
  324. .get("foo1")
  325. .as_ref()
  326. .unwrap()
  327. .token
  328. .as_ref()
  329. .unwrap(),
  330. "4"
  331. );
  332. Ok(())
  333. }
  334. }