feat: validate named configuration paths

This commit is contained in:
Dandaedre 2026-09-29 13:19:02 +02:00
parent 177337c0ae
commit dcdf958e9c
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
3 changed files with 126 additions and 3 deletions

View File

@ -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<Self, Self::Err> {
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<PathBuf>,
/// Explicit configuration supplied for this invocation, if any.
pub explicit: Option<PathBuf>,
}
impl ConfigPaths {
/// Resolve paths using the operating system's application-directory APIs.
pub fn discover(name: Option<&ConfigName>, explicit: Option<PathBuf>) -> Option<Self> {
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<PathBuf>,
) -> 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::<ConfigName>().unwrap().as_str(), accepted);
}
for rejected in [
"",
".",
"../work",
"work.toml",
"a/b",
"équipe",
"has space",
] {
assert!(
rejected.parse::<ConfigName>().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::<ConfigName>().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")));
}
}

View File

@ -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};

View File

@ -88,7 +88,7 @@ entry do not discard successful documents.
and applicability scopes.
- [ ] Implement exact precedence: embedded defaults < user `config.toml` < named
user `<config_name>.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.