Skip to main content

rings_node/
util.rs

1//! Utilities for configuration and build.
2
3use serde::Deserialize;
4use serde::Deserializer;
5use serde::Serialize;
6use serde::Serializer;
7
8#[cfg(feature = "node")]
9use crate::error::Error;
10
11#[allow(dead_code)]
12/// Serialize a value through Serde without an intermediate wrapper.
13pub fn serialize_forward<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
14where
15    T: Serialize,
16    S: Serializer,
17{
18    value.serialize(serializer)
19}
20
21#[allow(dead_code)]
22/// Deserialize a value through Serde without an intermediate wrapper.
23pub fn deserialize_forward<'de, T, D>(deserializer: D) -> Result<T, D::Error>
24where
25    T: Deserialize<'de>,
26    D: Deserializer<'de>,
27{
28    T::deserialize(deserializer)
29}
30
31/// build_version of program
32pub fn build_version() -> String {
33    let mut infos = vec![];
34    if let Some(version) = option_env!("CARGO_PKG_VERSION") {
35        infos.push(version);
36    };
37    if let Some(git_hash) = option_env!("GIT_SHORT_HASH") {
38        infos.push(git_hash);
39    }
40    infos.join("-")
41}
42
43/// Expand path with "~" to absolute path.
44#[cfg(feature = "node")]
45pub fn expand_home<P>(path: P) -> Result<std::path::PathBuf, Error>
46where P: AsRef<std::path::Path> {
47    let Ok(stripped) = path.as_ref().strip_prefix("~") else {
48        return Ok(path.as_ref().to_path_buf());
49    };
50
51    let Some(mut p) = home::home_dir() else {
52        return Err(Error::HomeDirError);
53    };
54
55    p.push(stripped);
56
57    Ok(p)
58}
59
60/// Create parent directory of a path if not exists.
61#[cfg(feature = "node")]
62pub fn ensure_parent_dir<P>(path: P) -> Result<(), Error>
63where P: AsRef<std::path::Path> {
64    let path = expand_home(path)?;
65    let parent = path.parent().ok_or(Error::ParentDirError)?;
66    if !parent.is_dir() {
67        std::fs::create_dir_all(parent).map_err(|e| Error::CreateFileError(e.to_string()))?;
68    };
69    Ok(())
70}
71
72#[cfg(feature = "node")]
73pub mod loader {
74    //! A module to help user load config from local file or remote url.
75
76    use std::io::Read;
77    use std::time::Duration;
78
79    use async_trait::async_trait;
80    use reqwest::Url;
81    use serde::de::DeserializeOwned;
82
83    use crate::seed::Seed;
84
85    const MAX_RESOURCE_BYTES: usize = 4 * 1_024 * 1_024;
86    const RESOURCE_FETCH_TIMEOUT: Duration = Duration::from_secs(15);
87
88    /// Load config from local file or remote url.
89    /// To use this trait, derive DeserializeOwned then implement this trait.
90    #[async_trait]
91    pub trait ResourceLoader {
92        /// Load config from local file or remote url.
93        async fn load(source: &str) -> anyhow::Result<Self>
94        where Self: Sized + DeserializeOwned {
95            let url = Url::parse(source).map_err(|e| anyhow::anyhow!("{}", e))?;
96
97            if url.scheme() == "file" {
98                let path = url
99                    .to_file_path()
100                    .map_err(|_| anyhow::anyhow!("Invalid file resource path"))?;
101                let file = std::fs::File::open(path)
102                    .map_err(|_| anyhow::anyhow!("Unable to read resource file"))?;
103                let mut bytes = Vec::new();
104                file.take((MAX_RESOURCE_BYTES as u64).saturating_add(1))
105                    .read_to_end(&mut bytes)
106                    .map_err(|_| anyhow::anyhow!("Unable to read resource file"))?;
107                if bytes.len() > MAX_RESOURCE_BYTES {
108                    anyhow::bail!("resource file exceeds maximum {MAX_RESOURCE_BYTES} bytes");
109                }
110                return serde_json::from_slice(&bytes).map_err(|e| anyhow::anyhow!("{}", e));
111            }
112
113            if !matches!(url.scheme(), "http" | "https") {
114                anyhow::bail!("unsupported resource scheme {}", url.scheme());
115            }
116            if !url.username().is_empty() || url.password().is_some() {
117                anyhow::bail!("resource URL must not contain userinfo credentials");
118            }
119            rings_network_policy::validate_public_url_host(&url)
120                .map_err(|e| anyhow::anyhow!("resource URL blocked by network policy: {e}"))?;
121            let host = url
122                .host_str()
123                .ok_or_else(|| anyhow::anyhow!("resource URL missing host"))?;
124            let port = url
125                .port_or_known_default()
126                .ok_or_else(|| anyhow::anyhow!("resource URL missing port"))?;
127            let resolved: Vec<std::net::SocketAddr> = tokio::time::timeout(
128                RESOURCE_FETCH_TIMEOUT,
129                tokio::net::lookup_host((host, port)),
130            )
131            .await
132            .map_err(|_| anyhow::anyhow!("timed out resolving resource host"))?
133            .map_err(|e| anyhow::anyhow!("failed to resolve resource host: {e}"))?
134            .collect();
135            if resolved.is_empty()
136                || resolved
137                    .iter()
138                    .any(|addr| !rings_network_policy::is_public_ip(addr.ip()))
139            {
140                anyhow::bail!("resource URL resolved to a non-public IP address");
141            }
142
143            let mut builder = reqwest::Client::builder()
144                .timeout(RESOURCE_FETCH_TIMEOUT)
145                .redirect(reqwest::redirect::Policy::none())
146                .no_proxy();
147            if matches!(url.host(), Some(url::Host::Domain(_))) {
148                builder = builder.resolve_to_addrs(host, &resolved);
149            }
150            let client = builder
151                .build()
152                .map_err(|e| anyhow::anyhow!("failed to build HTTP client: {e}"))?;
153            let mut resp = client
154                .get(url)
155                .send()
156                .await
157                .map_err(|_| anyhow::anyhow!("failed to get resource from {}", source))?
158                .error_for_status()
159                .map_err(|_| anyhow::anyhow!("failed to get resource from {}", source))?;
160            if let Some(len) = resp.content_length() {
161                if len > MAX_RESOURCE_BYTES as u64 {
162                    anyhow::bail!(
163                        "remote resource length {len} exceeds maximum {MAX_RESOURCE_BYTES} bytes"
164                    );
165                }
166            }
167            let mut body = Vec::new();
168            while let Some(chunk) = resp
169                .chunk()
170                .await
171                .map_err(|_| anyhow::anyhow!("failed to load resource from {}", source))?
172            {
173                if body.len().saturating_add(chunk.len()) > MAX_RESOURCE_BYTES {
174                    anyhow::bail!("remote resource exceeds maximum {MAX_RESOURCE_BYTES} bytes");
175                }
176                body.extend_from_slice(&chunk);
177            }
178            serde_json::from_slice(&body)
179                .map_err(|_| anyhow::anyhow!("failed to load resource from {}", source))
180        }
181    }
182
183    impl ResourceLoader for Seed {}
184}
185
186#[cfg(test)]
187#[cfg(feature = "node")]
188mod tests {
189    use super::*;
190
191    #[test]
192    fn test_expand_home_with_tilde() {
193        let input = "~";
194        let mut expected = std::env::var("HOME").unwrap();
195        expected.push('/');
196        let result = expand_home(input).unwrap();
197        assert_eq!(result.to_str(), Some(expected.as_str()));
198    }
199
200    #[test]
201    fn test_expand_home_with_relative_path() {
202        let input = "~/path/to/file.txt";
203        let mut expected = std::env::var("HOME").unwrap();
204        expected.push_str("/path/to/file.txt");
205        let result = expand_home(input).unwrap();
206        assert_eq!(result.to_str(), Some(expected.as_str()));
207    }
208
209    #[test]
210    fn test_expand_home_with_absolute_path() {
211        let input = "/absolute/path/to/file.txt";
212        let expected = std::path::PathBuf::from(input);
213        let result = expand_home(input).unwrap();
214        assert_eq!(result, expected);
215    }
216
217    #[test]
218    fn test_expand_home_with_invalid_path() {
219        let input = "path/does/not/exist.txt";
220        let expected = std::path::PathBuf::from(input);
221        let result = expand_home(input).unwrap();
222        assert_eq!(result, expected);
223    }
224
225    #[test]
226    fn test_expand_home_with_empty_path() {
227        let input = "";
228        let expected = std::path::PathBuf::from("");
229        let result = expand_home(input).unwrap();
230        assert_eq!(result, expected);
231    }
232}