1use std::fs::OpenOptions;
9use std::io::Read;
10use std::path::{Component, Path, PathBuf};
11
12use relate_core::file_identity::{self, FileIdentity};
13use relate_core::{Error, Result};
14
15pub(crate) const DEFAULT_MAX_BYTES: u64 = 8_388_608;
16const MAX_BYTES_CEILING: u64 = 67_108_864;
17
18#[derive(Debug, Clone)]
20pub struct CsvPolicy {
21 root: Option<PathBuf>,
22 max_bytes: u64,
23}
24
25impl Default for CsvPolicy {
26 fn default() -> Self {
27 Self::new(None, None).expect("default CSV policy is valid")
28 }
29}
30
31pub(super) fn unavailable() -> Error {
32 Error::execution("LOAD CSV file unavailable")
33}
34
35fn invalid_config() -> Error {
38 Error::semantic("LOAD CSV invalid configuration")
39}
40
41#[derive(Debug)]
44pub(super) struct VerifiedTarget {
45 pub(super) path: PathBuf,
46 identity: FileIdentity,
47}
48
49fn confined(candidate: PathBuf, root: &Path) -> Option<VerifiedTarget> {
54 let target = candidate.canonicalize().ok()?;
55 if !target.starts_with(root) {
56 return None;
57 }
58 if !std::fs::symlink_metadata(&target).ok()?.is_file() {
61 return None;
62 }
63 let identity = file_identity::of_path(&target).ok()?;
64 Some(VerifiedTarget {
65 path: target,
66 identity,
67 })
68}
69
70#[cfg(windows)]
75fn windows_drive_path(url_path: &str) -> Result<&str> {
76 let drive_path = &url_path[1..];
77 let bytes = drive_path.as_bytes();
78 if bytes.len() < 3
79 || !bytes[0].is_ascii_alphabetic()
80 || bytes[1] != b':'
81 || bytes[2] != b'/'
82 || drive_path.contains('\\')
83 || drive_path[3..].contains(':')
84 {
85 return Err(unavailable());
86 }
87 Ok(drive_path)
88}
89
90impl CsvPolicy {
91 pub fn new(root: Option<PathBuf>, max_bytes: Option<u64>) -> Result<Self> {
94 let max_bytes = max_bytes.unwrap_or(DEFAULT_MAX_BYTES);
95 if !(1..=MAX_BYTES_CEILING).contains(&max_bytes) {
96 return Err(invalid_config());
97 }
98 let root = root
99 .map(|dir| {
100 let canonical = dir.canonicalize().map_err(|_| invalid_config())?;
101 if !canonical.is_dir() {
102 return Err(invalid_config());
103 }
104 Ok(canonical)
105 })
106 .transpose()?;
107 Ok(Self { root, max_bytes })
108 }
109
110 #[cfg(test)]
112 pub(crate) fn max_bytes(&self) -> u64 {
113 self.max_bytes
114 }
115
116 #[cfg(test)]
118 pub(crate) fn root(&self) -> Option<&Path> {
119 self.root.as_deref()
120 }
121
122 pub(super) fn target(&self, source: &str) -> Result<VerifiedTarget> {
123 let root = self.root.as_ref().ok_or_else(unavailable)?;
124 Self::classify(source, root)?
128 .into_iter()
129 .find_map(|candidate| confined(candidate, root))
130 .ok_or_else(unavailable)
131 }
132
133 fn classify(source: &str, root: &Path) -> Result<Vec<PathBuf>> {
149 if let Some(url_path) = source.strip_prefix("file://") {
150 if !url_path.starts_with('/')
153 || url_path.starts_with("//")
154 || url_path.contains(['?', '#', '%'])
155 {
156 return Err(unavailable());
157 }
158 #[cfg(windows)]
159 let url_path = windows_drive_path(url_path)?;
160 let path = Path::new(url_path);
161 if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
162 return Err(unavailable());
163 }
164 let relative = path.strip_prefix("/").unwrap_or(path);
170 Ok(vec![path.to_path_buf(), root.join(relative)])
171 } else {
172 let scheme = source.split_once(':').is_some_and(|(prefix, _)| {
173 prefix.starts_with(|c: char| c.is_ascii_alphabetic())
174 && prefix
175 .chars()
176 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
177 });
178 if scheme || source.contains(['?', '#']) {
179 return Err(unavailable());
180 }
181 let path = Path::new(source);
182 if path.as_os_str().is_empty()
183 || path.has_root()
184 || path
185 .components()
186 .any(|c| matches!(c, Component::ParentDir | Component::Prefix(_)))
187 {
188 return Err(unavailable());
189 }
190 Ok(vec![root.join(path)])
191 }
192 }
193
194 pub(super) fn read(&self, target: &VerifiedTarget) -> Result<String> {
195 let mut opts = OpenOptions::new();
196 opts.read(true);
197 file_identity::nofollow(&mut opts);
201 let file = opts.open(&target.path).map_err(|_| unavailable())?;
202 if file_identity::of_file(&file).map_err(|_| unavailable())? != target.identity
203 || !file.metadata().map_err(|_| unavailable())?.is_file()
204 {
205 return Err(unavailable());
206 }
207 let mut bytes = Vec::new();
208 file.take(self.max_bytes.saturating_add(1))
209 .read_to_end(&mut bytes)
210 .map_err(|_| unavailable())?;
211 if bytes.len() as u64 > self.max_bytes {
212 return Err(Error::execution("LOAD CSV file exceeds byte limit"));
213 }
214 String::from_utf8(bytes).map_err(|_| unavailable())
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::super::{local_file_url, test_root};
221 use super::*;
222 use std::fs;
223
224 #[test]
229 fn new_validates_byte_limit_and_root() {
230 let dir = test_root();
231 let root = dir.path();
232 let file = root.join("rows.csv");
233 fs::write(&file, "safe\n").unwrap();
234 for limit in [0, 67_108_865, u64::MAX] {
235 assert_eq!(
236 CsvPolicy::new(Some(root.to_path_buf()), Some(limit)).unwrap_err(),
237 invalid_config()
238 );
239 }
240 for invalid_root in [root.join("missing"), file] {
241 assert_eq!(
242 CsvPolicy::new(Some(invalid_root), None).unwrap_err(),
243 invalid_config()
244 );
245 }
246 let relative = CsvPolicy::new(Some(PathBuf::from(".")), None).unwrap();
249 assert!(relative.root.as_ref().unwrap().is_absolute());
250 assert!(CsvPolicy::new(None, Some(MAX_BYTES_CEILING)).is_ok());
251 }
252
253 #[cfg(windows)]
254 #[test]
255 fn local_drive_urls_are_absolute_and_restricted_to_the_csv_root() {
256 let dir = test_root();
257 let root = dir.path();
258 let inside = root.join("rows.csv");
259 fs::write(&inside, "safe\n").unwrap();
260 let outside = root.with_extension("outside.csv");
261 fs::write(&outside, "private\n").unwrap();
262 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
263 let url = local_file_url(&inside);
264 assert_eq!(
265 policy.target(&url).unwrap().path,
266 inside.canonicalize().unwrap()
267 );
268
269 let root_url = local_file_url(&root);
270 let outside_url = local_file_url(&outside);
271 for source in [
272 outside_url.as_str(),
273 &format!("{root_url}/../outside.csv"),
274 &format!(
275 "{root_url}/../{}/rows.csv",
276 root.file_name().unwrap().to_string_lossy()
277 ),
278 &url.replace("/rows.csv", "/rows%2ecsv"),
279 &url.replace("/rows.csv", "/rows.csv:stream"),
280 &format!("file:///{}", inside.display()),
281 &format!("file://{}", inside.display()),
282 "file://host/C:/rows.csv",
283 "file://C:\\rows.csv",
284 "file:////server/share/rows.csv",
285 r"file:///\\server\share\rows.csv",
286 r"file:///\\?\C:\rows.csv",
287 r"file:///\\.\C:\rows.csv",
288 "file:///C:rows.csv",
289 "C:rows.csv",
290 r"\rows.csv",
291 ] {
292 assert_eq!(
293 policy.target(source).unwrap_err(),
294 unavailable(),
295 "{source}"
296 );
297 }
298 fs::remove_file(outside).unwrap();
299 }
300
301 #[cfg(not(windows))]
302 #[test]
303 fn file_url_paths_resolve_against_the_policy_root() {
304 let dir = test_root();
305 let root = dir.path();
306 let inside = root.join("rows.csv");
307 fs::write(&inside, "safe\n").unwrap();
308 let outside = root.with_extension("outside.csv");
309 fs::write(&outside, "private\n").unwrap();
310 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
311 let canonical = inside.canonicalize().unwrap();
312
313 assert_eq!(
316 policy.target(&local_file_url(&inside)).unwrap().path,
317 canonical
318 );
319 assert_eq!(policy.target("file:///rows.csv").unwrap().path, canonical);
320
321 for source in [
323 "file:///missing.csv",
324 "file:///../rows.csv",
325 "file:///rows.csv/../rows.csv",
326 "file:////rows.csv",
327 "file://rows.csv",
328 &local_file_url(&outside),
329 ] {
330 assert_eq!(
331 policy.target(source).unwrap_err(),
332 unavailable(),
333 "{source}"
334 );
335 }
336 fs::remove_file(outside).unwrap();
337 }
338
339 #[cfg(unix)]
340 #[test]
341 fn read_denies_target_swapped_for_out_of_root_symlink() {
342 use std::os::unix::fs::symlink;
343
344 let dir = test_root();
345 let root = dir.path();
346 let outside_dir = test_root();
347 let outside = outside_dir.path();
348 fs::write(root.join("rows.csv"), "inside\n").unwrap();
349 fs::write(outside.join("outside.csv"), "outside\n").unwrap();
350 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
351 let target = policy.target("rows.csv").unwrap();
352
353 fs::remove_file(root.join("rows.csv")).unwrap();
354 symlink(outside.join("outside.csv"), root.join("rows.csv")).unwrap();
355 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
356 }
357
358 #[test]
359 fn read_denies_target_swapped_for_other_in_root_file() {
360 let dir = test_root();
361 let root = dir.path();
362 fs::write(root.join("rows.csv"), "one\n").unwrap();
363 fs::write(root.join("other.csv"), "two\n").unwrap();
364 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
365 let target = policy.target("rows.csv").unwrap();
366
367 fs::remove_file(root.join("rows.csv")).unwrap();
370 fs::rename(root.join("other.csv"), root.join("rows.csv")).unwrap();
371 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
372 }
373
374 #[cfg(unix)]
375 #[test]
376 fn read_denies_intermediate_directory_swap() {
377 use std::os::unix::fs::symlink;
378
379 let dir = test_root();
380 let root = dir.path();
381 let outside_dir = test_root();
382 let outside = outside_dir.path();
383 fs::create_dir(root.join("sub")).unwrap();
384 fs::write(root.join("sub/rows.csv"), "inside\n").unwrap();
385 fs::write(outside.join("rows.csv"), "outside\n").unwrap();
386 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
387 let target = policy.target("sub/rows.csv").unwrap();
388
389 fs::rename(root.join("sub"), root.join("sub-orig")).unwrap();
392 symlink(outside, root.join("sub")).unwrap();
393 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
394 }
395
396 #[test]
397 fn read_denies_mismatched_recorded_identity() {
398 let dir = test_root();
399 let root = dir.path();
400 let file = root.join("rows.csv");
401 fs::write(&file, "rows\n").unwrap();
402 let other = root.join("other.csv");
403 fs::write(&other, "other\n").unwrap();
404 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
405
406 let target = VerifiedTarget {
407 path: file.canonicalize().unwrap(),
408 identity: file_identity::of_path(&other.canonicalize().unwrap()).unwrap(),
409 };
410 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
411 }
412}