From dcdf958e9c8fc266a6a8b3746aeb58b60dee7b94 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 29 Sep 2026 13:19:02 +0200 Subject: [PATCH] feat: validate named configuration paths --- src/config.rs | 123 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 +- tasks.md | 2 +- 3 files changed, 126 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5ac1dd3..e6b3390 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,8 @@ //! Typed configuration consumed by the shared library. +use std::{fmt, path::PathBuf, str::FromStr}; + +use directories::ProjectDirs; use figment::{ Figment, providers::{Format, Toml}, @@ -11,6 +14,89 @@ use crate::Category; const EMBEDDED_CONFIG: &str = include_str!("../assets/config.toml"); const EMBEDDED_HEURISTICS: &str = include_str!("../assets/heuristics.toml"); +/// A validated named configuration without path syntax or a file extension. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ConfigName(String); + +impl ConfigName { + /// Return the validated name as text. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for ConfigName { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(formatter) + } +} + +impl FromStr for ConfigName { + type Err = ConfigNameError; + + fn from_str(value: &str) -> Result { + if value.is_empty() + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')) + { + return Err(ConfigNameError { + value: value.to_owned(), + }); + } + + Ok(Self(value.to_owned())) + } +} + +/// A rejected named-configuration selector. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error( + "invalid config name `{value}`; use only ASCII letters, digits, `_`, and `-` without an extension" +)] +pub struct ConfigNameError { + value: String, +} + +/// Files considered by the layered configuration loader. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigPaths { + /// Platform-specific John Slop configuration directory. + pub directory: PathBuf, + /// User-wide base configuration. + pub base: PathBuf, + /// Selected named user configuration, if any. + pub named: Option, + /// Explicit configuration supplied for this invocation, if any. + pub explicit: Option, +} + +impl ConfigPaths { + /// Resolve paths using the operating system's application-directory APIs. + pub fn discover(name: Option<&ConfigName>, explicit: Option) -> Option { + let directory = ProjectDirs::from("com", "idle-org", "john_slop")? + .config_dir() + .to_owned(); + Some(Self::in_directory(directory, name, explicit)) + } + + /// Resolve paths under a known directory, primarily for deterministic tests. + pub fn in_directory( + directory: PathBuf, + name: Option<&ConfigName>, + explicit: Option, + ) -> Self { + let base = directory.join("config.toml"); + let named = name.map(|name| directory.join(format!("{name}.toml"))); + Self { + directory, + base, + named, + explicit, + } + } +} + /// One configured Unicode-to-ASCII replacement. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -219,4 +305,41 @@ mod tests { && !rule.scope.content.is_empty() })); } + + #[test] + fn config_names_accept_only_safe_ascii_components() { + for accepted in ["work", "review_2", "strict-mode", "A1"] { + assert_eq!(accepted.parse::().unwrap().as_str(), accepted); + } + + for rejected in [ + "", + ".", + "../work", + "work.toml", + "a/b", + "équipe", + "has space", + ] { + assert!( + rejected.parse::().is_err(), + "accepted {rejected:?}" + ); + } + } + + #[test] + fn config_paths_keep_named_files_inside_the_config_directory() { + let directory = PathBuf::from("/configuration-root/john_slop"); + let name = "strict-mode".parse::().unwrap(); + let paths = ConfigPaths::in_directory( + directory.clone(), + Some(&name), + Some(PathBuf::from("project.toml")), + ); + + assert_eq!(paths.base, directory.join("config.toml")); + assert_eq!(paths.named, Some(directory.join("strict-mode.toml"))); + assert_eq!(paths.explicit, Some(PathBuf::from("project.toml"))); + } } diff --git a/src/lib.rs b/src/lib.rs index 17e3c29..95997b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,8 +13,8 @@ mod model; mod replacement; pub use config::{ - ConfidenceThresholds, Config, ContentKind, HeuristicRule, InputLimits, MatcherType, - ReplacementRule, RuleScope, + ConfidenceThresholds, Config, ConfigName, ConfigNameError, ConfigPaths, ContentKind, + HeuristicRule, InputLimits, MatcherType, ReplacementRule, RuleScope, }; pub use error::{InputError, InputResult}; pub use input::{Document, Documents}; diff --git a/tasks.md b/tasks.md index 08779f1..cb549d6 100644 --- a/tasks.md +++ b/tasks.md @@ -88,7 +88,7 @@ entry do not discard successful documents. and applicability scopes. - [ ] Implement exact precedence: embedded defaults < user `config.toml` < named user `.toml` < explicit `--config` < explicit CLI flags. -- [ ] Validate config names and refuse traversal, extensions, empty names, and +- [x] Validate config names and refuse traversal, extensions, empty names, and non-ASCII characters. Resolve the user path with platform APIs. - [ ] Implement merge-by-ID for rule/replacement tables rather than allowing positional array replacement to produce surprising partial configuration.