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        Self::try_new(value).expect("ValidatedFilePath validation failed")
55    }
56
57    #[must_use]
58    pub fn as_str(&self) -> &str {
59        &self.0
60    }
61
62    #[must_use]
63    pub fn extension(&self) -> Option<&str> {
64        self.0
65            .rsplit('.')
66            .next()
67            .filter(|_| self.0.contains('.') && !self.0.ends_with('.'))
68    }
69
70    #[must_use]
71    pub fn file_name(&self) -> Option<&str> {
72        self.0.rsplit(['/', '\\']).next().filter(|s| !s.is_empty())
73    }
74}
75
76impl fmt::Display for ValidatedFilePath {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        write!(f, "{}", self.0)
79    }
80}
81
82impl TryFrom<String> for ValidatedFilePath {
83    type Error = IdValidationError;
84
85    fn try_from(s: String) -> Result<Self, Self::Error> {
86        Self::try_new(s)
87    }
88}
89
90impl TryFrom<&str> for ValidatedFilePath {
91    type Error = IdValidationError;
92
93    fn try_from(s: &str) -> Result<Self, Self::Error> {
94        Self::try_new(s)
95    }
96}
97
98impl std::str::FromStr for ValidatedFilePath {
99    type Err = IdValidationError;
100
101    fn from_str(s: &str) -> Result<Self, Self::Err> {
102        Self::try_new(s)
103    }
104}
105
106impl AsRef<str> for ValidatedFilePath {
107    fn as_ref(&self) -> &str {
108        &self.0
109    }
110}
111
112impl<'de> Deserialize<'de> for ValidatedFilePath {
113    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
114    where
115        D: serde::Deserializer<'de>,
116    {
117        let s = String::deserialize(deserializer)?;
118        Self::try_new(s).map_err(serde::de::Error::custom)
119    }
120}
121
122impl ToDbValue for ValidatedFilePath {
123    fn to_db_value(&self) -> DbValue {
124        DbValue::String(self.0.clone())
125    }
126}
127
128impl ToDbValue for &ValidatedFilePath {
129    fn to_db_value(&self) -> DbValue {
130        DbValue::String(self.0.clone())
131    }
132}