Skip to main content

systemprompt_identifiers/
path.rs

1//! Validated file path type.
2
3use crate::error::IdValidationError;
4use crate::{DbValue, ToDbValue};
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
9#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
10#[cfg_attr(feature = "sqlx", sqlx(transparent))]
11#[serde(transparent)]
12pub struct ValidatedFilePath(String);
13
14impl ValidatedFilePath {
15    pub fn try_new(value: impl Into<String>) -> Result<Self, IdValidationError> {
16        let value = value.into();
17        if value.is_empty() {
18            return Err(IdValidationError::empty("ValidatedFilePath"));
19        }
20        if value.contains('\0') {
21            return Err(IdValidationError::invalid(
22                "ValidatedFilePath",
23                "cannot contain null bytes",
24            ));
25        }
26        for component in value.split(['/', '\\']) {
27            if component == ".." {
28                return Err(IdValidationError::invalid(
29                    "ValidatedFilePath",
30                    "cannot contain '..' path traversal",
31                ));
32            }
33            let lower = component.to_lowercase();
34            if lower.contains("%2e%2e") || lower.contains("%2e.") || lower.contains(".%2e") {
35                return Err(IdValidationError::invalid(
36                    "ValidatedFilePath",
37                    "cannot contain encoded path traversal sequences",
38                ));
39            }
40        }
41        let lower_value = value.to_lowercase();
42        if lower_value.contains("%252e") {
43            return Err(IdValidationError::invalid(
44                "ValidatedFilePath",
45                "cannot contain double-encoded path sequences",
46            ));
47        }
48        Ok(Self(value))
49    }
50
51    #[must_use]
52    #[allow(clippy::expect_used)]
53    pub fn new(value: impl Into<String>) -> Self {
54        // SAFETY: `new` is the infallible constructor reserved for inputs the caller
55        // has already validated (compile-time literals, values that
56        // round-tripped through `try_new` at a boundary). Untrusted input must
57        // go through `try_new`.
58        Self::try_new(value).expect("ValidatedFilePath validation failed")
59    }
60
61    #[must_use]
62    pub fn as_str(&self) -> &str {
63        &self.0
64    }
65
66    #[must_use]
67    pub fn extension(&self) -> Option<&str> {
68        self.0
69            .rsplit('.')
70            .next()
71            .filter(|_| self.0.contains('.') && !self.0.ends_with('.'))
72    }
73
74    #[must_use]
75    pub fn file_name(&self) -> Option<&str> {
76        self.0.rsplit(['/', '\\']).next().filter(|s| !s.is_empty())
77    }
78}
79
80impl fmt::Display for ValidatedFilePath {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(f, "{}", self.0)
83    }
84}
85
86impl TryFrom<String> for ValidatedFilePath {
87    type Error = IdValidationError;
88
89    fn try_from(s: String) -> Result<Self, Self::Error> {
90        Self::try_new(s)
91    }
92}
93
94impl TryFrom<&str> for ValidatedFilePath {
95    type Error = IdValidationError;
96
97    fn try_from(s: &str) -> Result<Self, Self::Error> {
98        Self::try_new(s)
99    }
100}
101
102impl std::str::FromStr for ValidatedFilePath {
103    type Err = IdValidationError;
104
105    fn from_str(s: &str) -> Result<Self, Self::Err> {
106        Self::try_new(s)
107    }
108}
109
110impl AsRef<str> for ValidatedFilePath {
111    fn as_ref(&self) -> &str {
112        &self.0
113    }
114}
115
116impl<'de> Deserialize<'de> for ValidatedFilePath {
117    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118    where
119        D: serde::Deserializer<'de>,
120    {
121        let s = String::deserialize(deserializer)?;
122        Self::try_new(s).map_err(serde::de::Error::custom)
123    }
124}
125
126impl ToDbValue for ValidatedFilePath {
127    fn to_db_value(&self) -> DbValue {
128        DbValue::String(self.0.clone())
129    }
130}
131
132impl ToDbValue for &ValidatedFilePath {
133    fn to_db_value(&self) -> DbValue {
134        DbValue::String(self.0.clone())
135    }
136}