1use std::fs::OpenOptions;
11use std::io::Read;
12use std::path::{Component, Path, PathBuf};
13use std::sync::Arc;
14
15use relate_core::file_identity::{self, FileIdentity};
16use relate_core::{Error, Result};
17
18use super::errors::{
19 byte_limit_exceeded, credentials_refused, malformed_url, not_enabled, not_utf8,
20};
21use super::remote::{CsvRemote, RemoteFailure, RemoteUrl};
22
23pub(crate) const DEFAULT_MAX_BYTES: u64 = 8_388_608;
24const MAX_BYTES_CEILING: u64 = 67_108_864;
25
26#[derive(Debug, Clone)]
29pub struct CsvPolicy {
30 root: Option<PathBuf>,
31 max_bytes: u64,
32 remote: Option<Arc<dyn CsvRemote>>,
35}
36
37impl Default for CsvPolicy {
38 fn default() -> Self {
39 Self::new(None, None).expect("default CSV policy is valid")
40 }
41}
42
43pub(super) fn unavailable() -> Error {
44 Error::execution("LOAD CSV file unavailable")
45}
46
47fn invalid_config() -> Error {
50 Error::semantic("LOAD CSV invalid configuration")
51}
52
53#[derive(Debug)]
56pub(super) struct VerifiedTarget {
57 pub(super) path: PathBuf,
58 identity: FileIdentity,
59}
60
61pub(super) struct RemoteTarget<'a> {
65 remote: &'a dyn CsvRemote,
66 url: &'a str,
67}
68
69fn confined(candidate: PathBuf, root: &Path) -> Option<VerifiedTarget> {
74 let target = candidate.canonicalize().ok()?;
75 if !target.starts_with(root) {
76 return None;
77 }
78 if !std::fs::symlink_metadata(&target).ok()?.is_file() {
81 return None;
82 }
83 let identity = file_identity::of_path(&target).ok()?;
84 Some(VerifiedTarget {
85 path: target,
86 identity,
87 })
88}
89
90#[cfg(windows)]
95fn windows_drive_path(url_path: &str) -> Result<&str> {
96 let drive_path = &url_path[1..];
97 let bytes = drive_path.as_bytes();
98 if bytes.len() < 3
99 || !bytes[0].is_ascii_alphabetic()
100 || bytes[1] != b':'
101 || bytes[2] != b'/'
102 || drive_path.contains('\\')
103 || drive_path[3..].contains(':')
104 {
105 return Err(unavailable());
106 }
107 Ok(drive_path)
108}
109
110impl CsvPolicy {
111 pub fn new(root: Option<PathBuf>, max_bytes: Option<u64>) -> Result<Self> {
114 let max_bytes = max_bytes.unwrap_or(DEFAULT_MAX_BYTES);
115 if !(1..=MAX_BYTES_CEILING).contains(&max_bytes) {
116 return Err(invalid_config());
117 }
118 let root = root
119 .map(|dir| {
120 let canonical = dir.canonicalize().map_err(|_| invalid_config())?;
121 if !canonical.is_dir() {
122 return Err(invalid_config());
123 }
124 Ok(canonical)
125 })
126 .transpose()?;
127 Ok(Self {
128 root,
129 max_bytes,
130 remote: None,
131 })
132 }
133
134 #[must_use]
139 pub fn with_remote(mut self, remote: Arc<dyn CsvRemote>) -> Self {
140 self.remote = Some(remote);
141 self
142 }
143
144 #[cfg(test)]
146 pub(crate) fn max_bytes(&self) -> u64 {
147 self.max_bytes
148 }
149
150 #[cfg(test)]
152 pub(crate) fn root(&self) -> Option<&Path> {
153 self.root.as_deref()
154 }
155
156 pub(super) fn target(&self, source: &str) -> Result<VerifiedTarget> {
157 let root = self.root.as_ref().ok_or_else(unavailable)?;
158 Self::classify(source, root)?
162 .into_iter()
163 .find_map(|candidate| confined(candidate, root))
164 .ok_or_else(unavailable)
165 }
166
167 fn classify(source: &str, root: &Path) -> Result<Vec<PathBuf>> {
183 if let Some(url_path) = source.strip_prefix("file://") {
184 if !url_path.starts_with('/')
187 || url_path.starts_with("//")
188 || url_path.contains(['?', '#', '%'])
189 {
190 return Err(unavailable());
191 }
192 #[cfg(windows)]
193 let url_path = windows_drive_path(url_path)?;
194 let path = Path::new(url_path);
195 if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
196 return Err(unavailable());
197 }
198 let relative = path.strip_prefix("/").unwrap_or(path);
204 Ok(vec![path.to_path_buf(), root.join(relative)])
205 } else {
206 let scheme = source.split_once(':').is_some_and(|(prefix, _)| {
207 prefix.starts_with(|c: char| c.is_ascii_alphabetic())
208 && prefix
209 .chars()
210 .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
211 });
212 if scheme || source.contains(['?', '#']) {
213 return Err(unavailable());
214 }
215 let path = Path::new(source);
216 if path.as_os_str().is_empty()
217 || path.has_root()
218 || path
219 .components()
220 .any(|c| matches!(c, Component::ParentDir | Component::Prefix(_)))
221 {
222 return Err(unavailable());
223 }
224 Ok(vec![root.join(path)])
225 }
226 }
227
228 fn within_limit(&self, len: usize) -> Result<()> {
231 if len as u64 > self.max_bytes {
232 return Err(byte_limit_exceeded());
233 }
234 Ok(())
235 }
236
237 pub(super) fn remote_target<'a>(
243 &'a self,
244 url: &RemoteUrl<'_>,
245 canonical: &'a str,
246 ) -> Result<RemoteTarget<'a>> {
247 let remote = self.remote.as_deref().ok_or_else(not_enabled)?;
248 if !url.is_well_formed() {
249 return Err(malformed_url());
250 }
251 if url.carries_credentials() {
252 return Err(credentials_refused());
253 }
254 Ok(RemoteTarget {
255 remote,
256 url: canonical,
257 })
258 }
259
260 pub(super) fn read_remote(&self, target: &RemoteTarget<'_>) -> Result<String> {
264 let bytes = target
265 .remote
266 .fetch(target.url, self.max_bytes)
267 .map_err(RemoteFailure::into_error)?;
268 self.within_limit(bytes.len())?;
269 String::from_utf8(bytes).map_err(|_| not_utf8())
270 }
271
272 pub(super) fn read(&self, target: &VerifiedTarget) -> Result<String> {
273 let mut opts = OpenOptions::new();
274 opts.read(true);
275 file_identity::nofollow(&mut opts);
279 let file = opts.open(&target.path).map_err(|_| unavailable())?;
280 if file_identity::of_file(&file).map_err(|_| unavailable())? != target.identity
281 || !file.metadata().map_err(|_| unavailable())?.is_file()
282 {
283 return Err(unavailable());
284 }
285 let mut bytes = Vec::new();
286 file.take(self.max_bytes.saturating_add(1))
287 .read_to_end(&mut bytes)
288 .map_err(|_| unavailable())?;
289 self.within_limit(bytes.len())?;
290 String::from_utf8(bytes).map_err(|_| unavailable())
291 }
292}
293
294#[cfg(test)]
295mod tests {
296 use super::super::{local_file_url, test_root};
297 use super::*;
298 use std::fs;
299
300 #[test]
305 fn new_validates_byte_limit_and_root() {
306 let dir = test_root();
307 let root = dir.path();
308 let file = root.join("rows.csv");
309 fs::write(&file, "safe\n").unwrap();
310 for limit in [0, 67_108_865, u64::MAX] {
311 assert_eq!(
312 CsvPolicy::new(Some(root.to_path_buf()), Some(limit)).unwrap_err(),
313 invalid_config()
314 );
315 }
316 for invalid_root in [root.join("missing"), file] {
317 assert_eq!(
318 CsvPolicy::new(Some(invalid_root), None).unwrap_err(),
319 invalid_config()
320 );
321 }
322 let relative = CsvPolicy::new(Some(PathBuf::from(".")), None).unwrap();
325 assert!(relative.root.as_ref().unwrap().is_absolute());
326 assert!(CsvPolicy::new(None, Some(MAX_BYTES_CEILING)).is_ok());
327 }
328
329 #[cfg(windows)]
330 #[test]
331 fn local_drive_urls_are_absolute_and_restricted_to_the_csv_root() {
332 let dir = test_root();
333 let root = dir.path();
334 let inside = root.join("rows.csv");
335 fs::write(&inside, "safe\n").unwrap();
336 let outside = root.with_extension("outside.csv");
337 fs::write(&outside, "private\n").unwrap();
338 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
339 let url = local_file_url(&inside);
340 assert_eq!(
341 policy.target(&url).unwrap().path,
342 inside.canonicalize().unwrap()
343 );
344
345 let root_url = local_file_url(&root);
346 let outside_url = local_file_url(&outside);
347 for source in [
348 outside_url.as_str(),
349 &format!("{root_url}/../outside.csv"),
350 &format!(
351 "{root_url}/../{}/rows.csv",
352 root.file_name().unwrap().to_string_lossy()
353 ),
354 &url.replace("/rows.csv", "/rows%2ecsv"),
355 &url.replace("/rows.csv", "/rows.csv:stream"),
356 &format!("file:///{}", inside.display()),
357 &format!("file://{}", inside.display()),
358 "file://host/C:/rows.csv",
359 "file://C:\\rows.csv",
360 "file:////server/share/rows.csv",
361 r"file:///\\server\share\rows.csv",
362 r"file:///\\?\C:\rows.csv",
363 r"file:///\\.\C:\rows.csv",
364 "file:///C:rows.csv",
365 "C:rows.csv",
366 r"\rows.csv",
367 ] {
368 assert_eq!(
369 policy.target(source).unwrap_err(),
370 unavailable(),
371 "{source}"
372 );
373 }
374 fs::remove_file(outside).unwrap();
375 }
376
377 #[cfg(not(windows))]
378 #[test]
379 fn file_url_paths_resolve_against_the_policy_root() {
380 let dir = test_root();
381 let root = dir.path();
382 let inside = root.join("rows.csv");
383 fs::write(&inside, "safe\n").unwrap();
384 let outside = root.with_extension("outside.csv");
385 fs::write(&outside, "private\n").unwrap();
386 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
387 let canonical = inside.canonicalize().unwrap();
388
389 assert_eq!(
392 policy.target(&local_file_url(&inside)).unwrap().path,
393 canonical
394 );
395 assert_eq!(policy.target("file:///rows.csv").unwrap().path, canonical);
396
397 for source in [
399 "file:///missing.csv",
400 "file:///../rows.csv",
401 "file:///rows.csv/../rows.csv",
402 "file:////rows.csv",
403 "file://rows.csv",
404 &local_file_url(&outside),
405 ] {
406 assert_eq!(
407 policy.target(source).unwrap_err(),
408 unavailable(),
409 "{source}"
410 );
411 }
412 fs::remove_file(outside).unwrap();
413 }
414
415 #[cfg(unix)]
416 #[test]
417 fn read_denies_target_swapped_for_out_of_root_symlink() {
418 use std::os::unix::fs::symlink;
419
420 let dir = test_root();
421 let root = dir.path();
422 let outside_dir = test_root();
423 let outside = outside_dir.path();
424 fs::write(root.join("rows.csv"), "inside\n").unwrap();
425 fs::write(outside.join("outside.csv"), "outside\n").unwrap();
426 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
427 let target = policy.target("rows.csv").unwrap();
428
429 fs::remove_file(root.join("rows.csv")).unwrap();
430 symlink(outside.join("outside.csv"), root.join("rows.csv")).unwrap();
431 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
432 }
433
434 #[test]
435 fn read_denies_target_swapped_for_other_in_root_file() {
436 let dir = test_root();
437 let root = dir.path();
438 fs::write(root.join("rows.csv"), "one\n").unwrap();
439 fs::write(root.join("other.csv"), "two\n").unwrap();
440 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
441 let target = policy.target("rows.csv").unwrap();
442
443 fs::remove_file(root.join("rows.csv")).unwrap();
446 fs::rename(root.join("other.csv"), root.join("rows.csv")).unwrap();
447 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
448 }
449
450 #[cfg(unix)]
451 #[test]
452 fn read_denies_intermediate_directory_swap() {
453 use std::os::unix::fs::symlink;
454
455 let dir = test_root();
456 let root = dir.path();
457 let outside_dir = test_root();
458 let outside = outside_dir.path();
459 fs::create_dir(root.join("sub")).unwrap();
460 fs::write(root.join("sub/rows.csv"), "inside\n").unwrap();
461 fs::write(outside.join("rows.csv"), "outside\n").unwrap();
462 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
463 let target = policy.target("sub/rows.csv").unwrap();
464
465 fs::rename(root.join("sub"), root.join("sub-orig")).unwrap();
468 symlink(outside, root.join("sub")).unwrap();
469 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
470 }
471
472 #[test]
473 fn read_denies_mismatched_recorded_identity() {
474 let dir = test_root();
475 let root = dir.path();
476 let file = root.join("rows.csv");
477 fs::write(&file, "rows\n").unwrap();
478 let other = root.join("other.csv");
479 fs::write(&other, "other\n").unwrap();
480 let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
481
482 let target = VerifiedTarget {
483 path: file.canonicalize().unwrap(),
484 identity: file_identity::of_path(&other.canonicalize().unwrap()).unwrap(),
485 };
486 assert_eq!(policy.read(&target).unwrap_err(), unavailable());
487 }
488}