roneocratesroneo-coresrcsettings.rs
0518da6beb3fd562b82c5b5c2798b72e0d1591b2- use std::env;
- use std::fs;
- use std::path::{Path, PathBuf};
- use indexmap::IndexMap;
- use serde_json::Value as JsonValue;
- use crate::config::yaml_to_json;
- use crate::error::{Result, RoneoError};
- /// Copier-compatible user settings (`settings.yml`).
- ///
- /// Discovered from (in order):
- /// 1. `$RONEO_SETTINGS_PATH`
- /// 2. `$COPIER_SETTINGS_PATH`
- /// 3. `~/.config/roneo/settings.yml`
- /// 4. `~/.config/copier/settings.yml`
- #[derive(Debug, Clone, Default)]
- pub struct UserSettings {
- /// Global default answers applied whenever a question has no explicit CLI `-d` or previous answer.
- pub defaults: IndexMap<String, JsonValue>,
- /// Trusted template path/URL prefixes (exact match or prefix match ending with `/` or `:`).
- pub trust: Vec<String>,
- }
- impl UserSettings {
- /// Load user settings from the standard environment/config locations, if present.
- pub fn load_default() -> Self {
- let Some(path) = find_settings_path() else {
- return Self::default();
- };
- Self::load_from_file(&path).unwrap_or_default()
- }
- /// Load user settings from an explicit YAML file.
- pub fn load_from_file(path: &Path) -> Result<Self> {
- let raw = fs::read_to_string(path).map_err(|e| RoneoError::io(path, e))?;
- Self::parse_yaml(&raw)
- }
- pub fn parse_yaml(raw: &str) -> Result<Self> {
- if raw.trim().is_empty() {
- return Ok(Self::default());
- }
- let val: serde_yaml_ng::Value = serde_yaml_ng::from_str(raw)?;
- let Some(map) = val.as_mapping() else {
- return Err(RoneoError::InvalidConfig(
- "User settings file must be a YAML mapping".into(),
- ));
- };
- let mut settings = Self::default();
- if let Some(defs) = map
- .get(serde_yaml_ng::Value::String("defaults".into()))
- .and_then(serde_yaml_ng::Value::as_mapping)
- {
- for (k, v) in defs {
- if let Some(key) = k.as_str() {
- settings.defaults.insert(key.to_string(), yaml_to_json(v)?);
- }
- }
- }
- if let Some(trust_seq) = map
- .get(serde_yaml_ng::Value::String("trust".into()))
- .and_then(serde_yaml_ng::Value::as_sequence)
- {
- for item in trust_seq {
- if let Some(s) = item.as_str() {
- settings.trust.push(s.to_string());
- }
- }
- }
- Ok(settings)
- }
- /// Returns `true` if `original_src` or `resolved_src` matches any trusted repository rule,
- /// enforcing Copier v9.18.2 RFC 3986 §2.3 safe-URL validation and `..` path normalization
- /// to prevent trust bypass via URL traversal or percent-encoding.
- pub fn is_trusted(&self, original_src: &str, resolved_src: &str) -> bool {
- self.trust.iter().any(|rule| {
- matches_trust_rule(rule, original_src) || matches_trust_rule(rule, resolved_src)
- })
- }
- }
- fn matches_trust_rule(rule: &str, candidate: &str) -> bool {
- if rule.is_empty() || candidate.is_empty() {
- return false;
- }
- if is_safe_url(candidate) && is_safe_url(rule) {
- let norm_cand = normalize_trust_ref(candidate);
- let norm_rule = normalize_trust_ref(rule);
- if rule.ends_with('/') || rule.ends_with(':') {
- norm_cand.starts_with(&norm_rule)
- } else {
- norm_cand == norm_rule
- }
- } else {
- // Unsafe URL characters (e.g., `%2e%2e`, `?`, `#`, `@` in path) require exact verbatim match.
- candidate == rule
- }
- }
- fn is_url_style(url: &str) -> bool {
- url.contains("://")
- || url.starts_with("gh:")
- || url.starts_with("gl:")
- || url.starts_with("git+")
- }
- /// Distinguish Git SCP-like remotes (`[user@]host:path`) from Windows drive paths (`C:\...`).
- fn is_scp_style(url: &str) -> bool {
- if is_url_style(url) {
- return false;
- }
- let bytes = url.as_bytes();
- if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
- return false;
- }
- let Some((left, right)) = url.split_once(':') else {
- return false;
- };
- !left.is_empty()
- && !right.is_empty()
- && !left.contains('/')
- && !left.contains('\\')
- && !left.chars().any(char::is_whitespace)
- }
- /// Copier v9.18.2 RFC 3986 §2.3 check: URL/SCP path segments may only contain unreserved
- /// characters (`A-Za-z0-9._~-`). Local filesystem paths are always considered safe.
- fn is_safe_url(url: &str) -> bool {
- let path = if is_url_style(url) {
- if let Some(idx) = url.find("://") {
- let after_scheme = &url[idx + 3..];
- // Reject query/fragment in safe prefix check (force exact match).
- if after_scheme.contains('?') || after_scheme.contains('#') {
- return false;
- }
- match after_scheme.find('/') {
- Some(slash) => &after_scheme[slash..],
- None => "",
- }
- } else if let Some((_, rest)) = url.split_once(':') {
- if rest.contains('?') || rest.contains('#') {
- return false;
- }
- rest
- } else {
- ""
- }
- } else if is_scp_style(url) {
- let (_, rest) = url.split_once(':').unwrap_or(("", ""));
- if rest.contains('?') || rest.contains('#') {
- return false;
- }
- rest
- } else {
- return true;
- };
- path.split('/').filter(|seg| !seg.is_empty()).all(|seg| {
- seg.bytes()
- .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'~' | b'-'))
- })
- }
- fn normalize_trust_ref(url: &str) -> String {
- if is_url_style(url) {
- if let Some(idx) = url.find("://") {
- let prefix_end = idx + 3;
- let after_scheme = &url[prefix_end..];
- return match after_scheme.find('/') {
- Some(slash) => {
- let host = &url[..prefix_end + slash];
- let path = &after_scheme[slash..];
- format!("{host}{}", normalize_posix_path(path))
- }
- None => url.to_string(),
- };
- }
- if let Some((alias, rest)) = url.split_once(':') {
- return format!("{alias}:{}", normalize_posix_path(rest));
- }
- }
- if is_scp_style(url)
- && let Some((host, path)) = url.split_once(':')
- {
- return format!("{host}:{}", normalize_posix_path(path));
- }
- let expanded = expand_tilde(url);
- normalize_posix_path(&expanded)
- }
- /// Collapse `.` and `..` segments and redundant `/` while preserving leading & trailing `/`.
- fn normalize_posix_path(path: &str) -> String {
- let leading_slash = path.starts_with('/');
- let trailing_slash = path.ends_with('/') && path.len() > 1;
- let mut stack: Vec<&str> = Vec::new();
- for seg in path.split('/') {
- match seg {
- "" | "." => {}
- ".." => {
- if let Some(&last) = stack.last() {
- if last != ".." {
- stack.pop();
- } else if !leading_slash {
- stack.push("..");
- }
- } else if !leading_slash {
- stack.push("..");
- }
- }
- other => stack.push(other),
- }
- }
- let mut out = String::with_capacity(path.len());
- if leading_slash {
- out.push('/');
- }
- out.push_str(&stack.join("/"));
- if trailing_slash && !out.ends_with('/') {
- out.push('/');
- }
- out
- }
- fn expand_tilde(path: &str) -> String {
- if let Some(rest) = path.strip_prefix("~/")
- && let Ok(home) = env::var("HOME")
- {
- return format!("{home}/{rest}");
- }
- path.to_string()
- }
- fn find_settings_path() -> Option<PathBuf> {
- for var in ["RONEO_SETTINGS_PATH", "COPIER_SETTINGS_PATH"] {
- if let Ok(p) = env::var(var)
- && !p.trim().is_empty()
- {
- let pb = PathBuf::from(p);
- if pb.is_file() {
- return Some(pb);
- }
- }
- }
- let home = env::var("HOME").or_else(|_| env::var("USERPROFILE")).ok()?;
- for rel in [".config/roneo/settings.yml", ".config/copier/settings.yml"] {
- let candidate = PathBuf::from(&home).join(rel);
- if candidate.is_file() {
- return Some(candidate);
- }
- }
- None
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn parses_defaults_and_trust_prefixes_with_security_checks() {
- let settings = UserSettings::parse_yaml(
- r"
- defaults:
- author: Alice
- year: 2026
- trust:
- - /srv/trusted/
- - gh:my-user/exact-repo
- - https://github.com/my-org/
- - git@gitlab.com:my-org/
- ",
- )
- .unwrap();
- assert_eq!(
- settings.defaults.get("author"),
- Some(&serde_json::json!("Alice"))
- );
- assert!(settings.is_trusted("/srv/trusted/templates/app", "/srv/trusted/templates/app"));
- assert!(!settings.is_trusted("/srv/other/repo", "/srv/other/repo"));
- assert!(settings.is_trusted(
- "gh:my-user/exact-repo",
- "https://github.com/my-user/exact-repo.git"
- ));
- assert!(!settings.is_trusted(
- "gh:my-user/exact-repo-2",
- "https://github.com/my-user/exact-repo-2.git"
- ));
- // Security checks (Copier v9.17 / v9.18.2):
- // 1. Traversal via `..` must NOT bypass trusted prefix!
- assert!(!settings.is_trusted(
- "https://github.com/my-org/../evil/repo.git",
- "https://github.com/my-org/../evil/repo.git"
- ));
- assert!(!settings.is_trusted(
- "git@gitlab.com:my-org/../evil/repo.git",
- "git@gitlab.com:my-org/../evil/repo.git"
- ));
- // 2. Percent-encoded traversal (`%2e%2e`) is NOT RFC 3986 unreserved -> rejected!
- assert!(!settings.is_trusted(
- "https://github.com/my-org/%2e%2e/evil/repo.git",
- "https://github.com/my-org/%2e%2e/evil/repo.git"
- ));
- // 3. Valid URL under trusted prefix passes!
- assert!(settings.is_trusted(
- "https://github.com/my-org/good-template.git",
- "https://github.com/my-org/good-template.git"
- ));
- assert!(settings.is_trusted(
- "git@gitlab.com:my-org/good-template.git",
- "git@gitlab.com:my-org/good-template.git"
- ));
- }
- }