forgeFRENBrowse the repositories

roneocratesroneo-coresrcsettings.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

321 lines · 10.3 KiBRustRaw
  1. use std::env;
  2. use std::fs;
  3. use std::path::{Path, PathBuf};
  4. use indexmap::IndexMap;
  5. use serde_json::Value as JsonValue;
  6. use crate::config::yaml_to_json;
  7. use crate::error::{Result, RoneoError};
  8. /// Copier-compatible user settings (`settings.yml`).
  9. ///
  10. /// Discovered from (in order):
  11. /// 1. `$RONEO_SETTINGS_PATH`
  12. /// 2. `$COPIER_SETTINGS_PATH`
  13. /// 3. `~/.config/roneo/settings.yml`
  14. /// 4. `~/.config/copier/settings.yml`
  15. #[derive(Debug, Clone, Default)]
  16. pub struct UserSettings {
  17. /// Global default answers applied whenever a question has no explicit CLI `-d` or previous answer.
  18. pub defaults: IndexMap<String, JsonValue>,
  19. /// Trusted template path/URL prefixes (exact match or prefix match ending with `/` or `:`).
  20. pub trust: Vec<String>,
  21. }
  22. impl UserSettings {
  23. /// Load user settings from the standard environment/config locations, if present.
  24. pub fn load_default() -> Self {
  25. let Some(path) = find_settings_path() else {
  26. return Self::default();
  27. };
  28. Self::load_from_file(&path).unwrap_or_default()
  29. }
  30. /// Load user settings from an explicit YAML file.
  31. pub fn load_from_file(path: &Path) -> Result<Self> {
  32. let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?;
  33. Self::parse_yaml(&raw)
  34. }
  35. pub fn parse_yaml(raw: &str) -> Result<Self> {
  36. if raw.trim().is_empty() {
  37. return Ok(Self::default());
  38. }
  39. let val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?;
  40. let Some(map) = val.as_mapping() else {
  41. return Err(RoneoError::InvalidConfig(
  42. "User settings file must be a YAML mapping".into(),
  43. ));
  44. };
  45. let mut settings = Self::default();
  46. if let Some(defs) = map
  47. .get(serde_yaml_ng::Value::String("defaults".into()))
  48. .and_then(serde_yaml_ng::Value::as_mapping)
  49. {
  50. for (k, v) in defs {
  51. if let Some(key) = k.as_str() {
  52. settings.defaults.insert(key.to_string(), yaml_to_json(v)?);
  53. }
  54. }
  55. }
  56. if let Some(trust_seq) = map
  57. .get(serde_yaml_ng::Value::String("trust".into()))
  58. .and_then(serde_yaml_ng::Value::as_sequence)
  59. {
  60. for item in trust_seq {
  61. if let Some(s) = item.as_str() {
  62. settings.trust.push(s.to_string());
  63. }
  64. }
  65. }
  66. Ok(settings)
  67. }
  68. /// Returns `true` if `original_src` or `resolved_src` matches any trusted repository rule,
  69. /// enforcing Copier v9.18.2 RFC 3986 §2.3 safe-URL validation and `..` path normalization
  70. /// to prevent trust bypass via URL traversal or percent-encoding.
  71. pub fn is_trusted(&self, original_src: &str, resolved_src: &str) -> bool {
  72. self.trust.iter().any(|rule| {
  73. matches_trust_rule(rule, original_src) || matches_trust_rule(rule, resolved_src)
  74. })
  75. }
  76. }
  77. fn matches_trust_rule(rule: &str, candidate: &str) -> bool {
  78. if rule.is_empty() || candidate.is_empty() {
  79. return false;
  80. }
  81. if is_safe_url(candidate) && is_safe_url(rule) {
  82. let norm_cand = normalize_trust_ref(candidate);
  83. let norm_rule = normalize_trust_ref(rule);
  84. if rule.ends_with('/') || rule.ends_with(':') {
  85. norm_cand.starts_with(&norm_rule)
  86. } else {
  87. norm_cand == norm_rule
  88. }
  89. } else {
  90. // Unsafe URL characters (e.g., `%2e%2e`, `?`, `#`, `@` in path) require exact verbatim match.
  91. candidate == rule
  92. }
  93. }
  94. fn is_url_style(url: &str) -> bool {
  95. url.contains("://")
  96. || url.starts_with("gh:")
  97. || url.starts_with("gl:")
  98. || url.starts_with("git+")
  99. }
  100. /// Distinguish Git SCP-like remotes (`[user@]host:path`) from Windows drive paths (`C:\...`).
  101. fn is_scp_style(url: &str) -> bool {
  102. if is_url_style(url) {
  103. return false;
  104. }
  105. let bytes = url.as_bytes();
  106. if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
  107. return false;
  108. }
  109. let Some((left, right)) = url.split_once(':') else {
  110. return false;
  111. };
  112. !left.is_empty()
  113. && !right.is_empty()
  114. && !left.contains('/')
  115. && !left.contains('\\')
  116. && !left.chars().any(char::is_whitespace)
  117. }
  118. /// Copier v9.18.2 RFC 3986 §2.3 check: URL/SCP path segments may only contain unreserved
  119. /// characters (`A-Za-z0-9._~-`). Local filesystem paths are always considered safe.
  120. fn is_safe_url(url: &str) -> bool {
  121. let path = if is_url_style(url) {
  122. if let Some(idx) = url.find("://") {
  123. let after_scheme = &url[idx + 3..];
  124. // Reject query/fragment in safe prefix check (force exact match).
  125. if after_scheme.contains('?') || after_scheme.contains('#') {
  126. return false;
  127. }
  128. match after_scheme.find('/') {
  129. Some(slash) => &after_scheme[slash..],
  130. None => "",
  131. }
  132. } else if let Some((_, rest)) = url.split_once(':') {
  133. if rest.contains('?') || rest.contains('#') {
  134. return false;
  135. }
  136. rest
  137. } else {
  138. ""
  139. }
  140. } else if is_scp_style(url) {
  141. let (_, rest) = url.split_once(':').unwrap_or(("", ""));
  142. if rest.contains('?') || rest.contains('#') {
  143. return false;
  144. }
  145. rest
  146. } else {
  147. return true;
  148. };
  149. path.split('/').filter(|seg| !seg.is_empty()).all(|seg| {
  150. seg.bytes()
  151. .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-'))
  152. })
  153. }
  154. fn normalize_trust_ref(url: &str) -> String {
  155. if is_url_style(url) {
  156. if let Some(idx) = url.find("://") {
  157. let prefix_end = idx + 3;
  158. let after_scheme = &url[prefix_end..];
  159. return match after_scheme.find('/') {
  160. Some(slash) => {
  161. let host = &url[..prefix_end + slash];
  162. let path = &after_scheme[slash..];
  163. format!("{host}{}", normalize_posix_path(path))
  164. }
  165. None => url.to_string(),
  166. };
  167. }
  168. if let Some((alias, rest)) = url.split_once(':') {
  169. return format!("{alias}:{}", normalize_posix_path(rest));
  170. }
  171. }
  172. if is_scp_style(url)
  173. && let Some((host, path)) = url.split_once(':')
  174. {
  175. return format!("{host}:{}", normalize_posix_path(path));
  176. }
  177. let expanded = expand_tilde(url);
  178. normalize_posix_path(&expanded)
  179. }
  180. /// Collapse `.` and `..` segments and redundant `/` while preserving leading & trailing `/`.
  181. fn normalize_posix_path(path: &str) -> String {
  182. let leading_slash = path.starts_with('/');
  183. let trailing_slash = path.ends_with('/') && path.len() > 1;
  184. let mut stack: Vec<&str> = Vec::new();
  185. for seg in path.split('/') {
  186. match seg {
  187. "" | "." => {}
  188. ".." => {
  189. if let Some(&last) = stack.last() {
  190. if last != ".." {
  191. stack.pop();
  192. } else if !leading_slash {
  193. stack.push("..");
  194. }
  195. } else if !leading_slash {
  196. stack.push("..");
  197. }
  198. }
  199. other => stack.push(other),
  200. }
  201. }
  202. let mut out = String::with_capacity(path.len());
  203. if leading_slash {
  204. out.push('/');
  205. }
  206. out.push_str(&stack.join("/"));
  207. if trailing_slash && !out.ends_with('/') {
  208. out.push('/');
  209. }
  210. out
  211. }
  212. fn expand_tilde(path: &str) -> String {
  213. if let Some(rest) = path.strip_prefix("~/")
  214. && let Ok(home) = env::var("HOME")
  215. {
  216. return format!("{home}/{rest}");
  217. }
  218. path.to_string()
  219. }
  220. fn find_settings_path() -> Option<PathBuf> {
  221. for var in ["RONEO_SETTINGS_PATH", "COPIER_SETTINGS_PATH"] {
  222. if let Ok(p) = env::var(var)
  223. && !p.trim().is_empty()
  224. {
  225. let pb = PathBuf::from(p);
  226. if pb.is_file() {
  227. return Some(pb);
  228. }
  229. }
  230. }
  231. let home = env::var("HOME").or_else(|_| env::var("USERPROFILE")).ok()?;
  232. for rel in [".config/roneo/settings.yml", ".config/copier/settings.yml"] {
  233. let candidate = PathBuf::from(&home).join(rel);
  234. if candidate.is_file() {
  235. return Some(candidate);
  236. }
  237. }
  238. None
  239. }
  240. #[cfg(test)]
  241. mod tests {
  242. use super::*;
  243. #[test]
  244. fn parses_defaults_and_trust_prefixes_with_security_checks() {
  245. let settings = UserSettings::parse_yaml(
  246. r"
  247. defaults:
  248. author: Alice
  249. year: 2026
  250. trust:
  251. - /srv/trusted/
  252. - gh:my-user/exact-repo
  253. - https://github.com/my-org/
  254. - git@gitlab.com:my-org/
  255. ",
  256. )
  257. .unwrap();
  258. assert_eq!(
  259. settings.defaults.get("author"),
  260. Some(&serde_json::json!("Alice"))
  261. );
  262. assert!(settings.is_trusted("/srv/trusted/templates/app", "/srv/trusted/templates/app"));
  263. assert!(!settings.is_trusted("/srv/other/repo", "/srv/other/repo"));
  264. assert!(settings.is_trusted(
  265. "gh:my-user/exact-repo",
  266. "https://github.com/my-user/exact-repo.git"
  267. ));
  268. assert!(!settings.is_trusted(
  269. "gh:my-user/exact-repo-2",
  270. "https://github.com/my-user/exact-repo-2.git"
  271. ));
  272. // Security checks (Copier v9.17 / v9.18.2):
  273. // 1. Traversal via `..` must NOT bypass trusted prefix!
  274. assert!(!settings.is_trusted(
  275. "https://github.com/my-org/../evil/repo.git",
  276. "https://github.com/my-org/../evil/repo.git"
  277. ));
  278. assert!(!settings.is_trusted(
  279. "git@gitlab.com:my-org/../evil/repo.git",
  280. "git@gitlab.com:my-org/../evil/repo.git"
  281. ));
  282. // 2. Percent-encoded traversal (`%2e%2e`) is NOT RFC 3986 unreserved -> rejected!
  283. assert!(!settings.is_trusted(
  284. "https://github.com/my-org/%2e%2e/evil/repo.git",
  285. "https://github.com/my-org/%2e%2e/evil/repo.git"
  286. ));
  287. // 3. Valid URL under trusted prefix passes!
  288. assert!(settings.is_trusted(
  289. "https://github.com/my-org/good-template.git",
  290. "https://github.com/my-org/good-template.git"
  291. ));
  292. assert!(settings.is_trusted(
  293. "git@gitlab.com:my-org/good-template.git",
  294. "git@gitlab.com:my-org/good-template.git"
  295. ));
  296. }
  297. }