vld 0.5.1

Type-safe runtime validation library for Rust, inspired by Zod
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
use serde_json::Value;
use std::fs;
use std::fs::File;
use std::io::Read as _;
use std::path::{Path, PathBuf};

use crate::error::{FileTypeKind, IssueCode, SizeOrigin, VldError, value_type_name};
use crate::primitives::path::{outside_base_error, resolve_within};
use crate::schema::VldSchema;
#[cfg(feature = "file-advanced")]
use md5::{Digest as _, Md5};
#[cfg(feature = "file-advanced")]
use sha2::Sha256;

#[cfg(feature = "file-advanced")]
fn digest_to_hex(output: impl AsRef<[u8]>) -> String {
    output
        .as_ref()
        .iter()
        .map(|b| format!("{:02x}", b))
        .collect()
}

/// A file that passed every check of a `vld::file()` schema.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidatedFile {
    path: PathBuf,
    size: u64,
    media_type: Option<String>,
    extension: Option<String>,
    bytes: Option<Vec<u8>>,
}

/// Whether a validated file keeps its contents in memory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileStorage {
    /// Only the path is kept; read the file with `read_bytes()` / `open()`.
    PathOnly,
    /// The contents were read during validation and are kept.
    InMemory,
}

impl ValidatedFile {
    /// Path of the file.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Size in bytes.
    pub fn size(&self) -> u64 {
        self.size
    }

    /// Media type detected from the magic bytes, if known.
    pub fn media_type(&self) -> Option<&str> {
        self.media_type.as_deref()
    }

    /// File name extension, lowercase, without the dot.
    pub fn extension(&self) -> Option<&str> {
        self.extension.as_deref()
    }

    /// How the contents are kept.
    pub fn storage(&self) -> FileStorage {
        if self.bytes.is_some() {
            FileStorage::InMemory
        } else {
            FileStorage::PathOnly
        }
    }

    /// The contents, when they were kept in memory.
    pub fn bytes(&self) -> Option<&[u8]> {
        self.bytes.as_deref()
    }

    /// Take the in-memory contents, if any.
    pub fn into_bytes(self) -> Option<Vec<u8>> {
        self.bytes
    }

    /// The contents: from memory, or read from disk.
    pub fn read_bytes(&self) -> Result<Vec<u8>, VldError> {
        if let Some(bytes) = &self.bytes {
            return Ok(bytes.clone());
        }
        fs::read(&self.path).map_err(|e| {
            VldError::single(
                IssueCode::IoError,
                format!("Failed to read file {}: {}", self.path.display(), e),
            )
        })
    }

    /// Open the file for reading.
    pub fn open(&self) -> Result<File, VldError> {
        File::open(&self.path).map_err(|e| {
            VldError::single(
                IssueCode::IoError,
                format!("Failed to open file {}: {}", self.path.display(), e),
            )
        })
    }
}

/// Schema for an uploaded / referenced file on the local filesystem. Created
/// via [`vld::file()`](crate::file) (read its security note: confine untrusted
/// paths with [`within`](Self::within)).
#[derive(Clone)]
pub struct ZFile {
    min_size: Option<u64>,
    max_size: Option<u64>,
    allowed_media_types: Vec<String>,
    denied_media_types: Vec<String>,
    allowed_extensions: Vec<String>,
    denied_extensions: Vec<String>,
    allowed_magic_types: Vec<String>,
    denied_magic_types: Vec<String>,
    sha256_hex: Option<String>,
    md5_hex: Option<String>,
    min_width: Option<u32>,
    max_width: Option<u32>,
    min_height: Option<u32>,
    max_height: Option<u32>,
    require_exif: bool,
    within_base: Option<PathBuf>,
    storage: FileStorage,
    custom_type_error: Option<String>,
}

impl ZFile {
    /// Create the schema (the same as its `vld::` constructor function).
    pub fn new() -> Self {
        Self {
            min_size: None,
            max_size: None,
            allowed_media_types: Vec::new(),
            denied_media_types: Vec::new(),
            allowed_extensions: Vec::new(),
            denied_extensions: Vec::new(),
            allowed_magic_types: Vec::new(),
            denied_magic_types: Vec::new(),
            sha256_hex: None,
            md5_hex: None,
            min_width: None,
            max_width: None,
            min_height: None,
            max_height: None,
            require_exif: false,
            within_base: None,
            storage: FileStorage::InMemory,
            custom_type_error: None,
        }
    }

    /// Message used when the input is not a path string or `{"path": ...}` object.
    pub fn type_error(mut self, msg: impl Into<String>) -> Self {
        self.custom_type_error = Some(msg.into());
        self
    }

    /// Size must be at least `bytes`.
    pub fn min_size(mut self, bytes: u64) -> Self {
        self.min_size = Some(bytes);
        self
    }

    /// Size must be at most `bytes`.
    pub fn max_size(mut self, bytes: u64) -> Self {
        self.max_size = Some(bytes);
        self
    }

    /// Size must be greater than zero.
    pub fn non_empty(self) -> Self {
        self.min_size(1)
    }

    /// Allow this media type (detected from the magic bytes).
    pub fn media_type(mut self, mt: impl Into<String>) -> Self {
        self.allowed_media_types
            .push(mt.into().to_ascii_lowercase());
        self
    }

    /// Allow these media types.
    pub fn media_types(mut self, types: &[&str]) -> Self {
        self.allowed_media_types
            .extend(types.iter().map(|s| s.to_ascii_lowercase()));
        self
    }

    /// Reject this media type.
    pub fn deny_media_type(mut self, mt: impl Into<String>) -> Self {
        self.denied_media_types.push(mt.into().to_ascii_lowercase());
        self
    }

    /// Allow this file name extension.
    pub fn extension(mut self, ext: impl Into<String>) -> Self {
        let normalized = ext.into().trim_start_matches('.').to_ascii_lowercase();
        self.allowed_extensions.push(normalized);
        self
    }

    /// Allow these file name extensions.
    pub fn extensions(mut self, exts: &[&str]) -> Self {
        self.allowed_extensions.extend(
            exts.iter()
                .map(|s| s.trim_start_matches('.').to_ascii_lowercase()),
        );
        self
    }

    /// Reject this file name extension.
    pub fn deny_extension(mut self, ext: impl Into<String>) -> Self {
        self.denied_extensions
            .push(ext.into().trim_start_matches('.').to_ascii_lowercase());
        self
    }

    /// Allow this type detected from the magic bytes (`"png"`, `"pdf"`, …).
    pub fn allow_magic_type(mut self, kind: impl Into<String>) -> Self {
        self.allowed_magic_types
            .push(kind.into().to_ascii_lowercase());
        self
    }

    /// Reject this type detected from the magic bytes.
    pub fn deny_magic_type(mut self, kind: impl Into<String>) -> Self {
        self.denied_magic_types
            .push(kind.into().to_ascii_lowercase());
        self
    }

    /// SHA-256 of the contents must equal `hex`.
    #[cfg(feature = "file-advanced")]
    pub fn sha256(mut self, hex: impl Into<String>) -> Self {
        self.sha256_hex = Some(hex.into().to_ascii_lowercase());
        self
    }

    /// MD5 of the contents must equal `hex`.
    #[cfg(feature = "file-advanced")]
    pub fn md5(mut self, hex: impl Into<String>) -> Self {
        self.md5_hex = Some(hex.into().to_ascii_lowercase());
        self
    }

    /// Image width must be at least `w` pixels.
    #[cfg(feature = "file-advanced")]
    pub fn min_width(mut self, w: u32) -> Self {
        self.min_width = Some(w);
        self
    }

    /// Image width must be at most `w` pixels.
    #[cfg(feature = "file-advanced")]
    pub fn max_width(mut self, w: u32) -> Self {
        self.max_width = Some(w);
        self
    }

    /// Image height must be at least `h` pixels.
    #[cfg(feature = "file-advanced")]
    pub fn min_height(mut self, h: u32) -> Self {
        self.min_height = Some(h);
        self
    }

    /// Image height must be at most `h` pixels.
    #[cfg(feature = "file-advanced")]
    pub fn max_height(mut self, h: u32) -> Self {
        self.max_height = Some(h);
        self
    }

    /// The image must carry EXIF metadata.
    #[cfg(feature = "file-advanced")]
    pub fn require_exif(mut self) -> Self {
        self.require_exif = true;
        self
    }

    /// Require the file to live inside `base` (same rules as
    /// [`ZPath::within`](crate::primitives::ZPath::within)): relative inputs are
    /// resolved against `base`, `..` and symlinks cannot escape it, and the
    /// returned [`ValidatedFile::path`] is the joined path.
    ///
    /// **Use this whenever the path comes from untrusted input** — without it
    /// any readable file (e.g. `{"path": "/etc/passwd"}`) is accepted.
    pub fn within(mut self, base: impl Into<PathBuf>) -> Self {
        self.within_base = Some(base.into());
        self
    }

    /// Store only file path and metadata in output.
    ///
    /// Use [`ValidatedFile::read_bytes`] / [`ValidatedFile::open`] to get content later.
    pub fn store_path_only(mut self) -> Self {
        self.storage = FileStorage::PathOnly;
        self
    }

    /// Store full file bytes in output (default mode).
    pub fn store_in_memory(mut self) -> Self {
        self.storage = FileStorage::InMemory;
        self
    }

    /// Validate the file at `path` directly (no JSON input).
    pub fn parse_path(&self, path: impl AsRef<Path>) -> Result<ValidatedFile, VldError> {
        self.parse_value(&Value::String(path.as_ref().to_string_lossy().to_string()))
    }
}

impl Default for ZFile {
    fn default() -> Self {
        Self::new()
    }
}

fn media_matches(actual: &str, rule: &str) -> bool {
    if let Some(prefix) = rule.strip_suffix("/*") {
        actual.starts_with(&(prefix.to_string() + "/"))
    } else {
        actual == rule
    }
}

fn extract_path(value: &Value) -> Result<&str, VldError> {
    match value {
        Value::String(s) => Ok(s.as_str()),
        Value::Object(obj) => obj.get("path").and_then(Value::as_str).ok_or_else(|| {
            VldError::from_code_with_value(
                IssueCode::InvalidType {
                    expected: "file".to_string(),
                    received: value_type_name(value),
                },
                value,
            )
        }),
        _ => Err(VldError::from_code_with_value(
            IssueCode::InvalidType {
                expected: "file".to_string(),
                received: value_type_name(value),
            },
            value,
        )),
    }
}

fn file_err(code: IssueCode, value: &Value) -> VldError {
    VldError::from_code_with_value(code, value)
}

fn not_allowed(kind: FileTypeKind, actual: &str, allowed: &[String], value: &Value) -> VldError {
    file_err(
        IssueCode::FileTypeNotAllowed {
            kind,
            actual: actual.to_string(),
            allowed: allowed.to_vec(),
        },
        value,
    )
}

fn denied(kind: FileTypeKind, actual: &str, value: &Value) -> VldError {
    file_err(
        IssueCode::FileTypeDenied {
            kind,
            actual: actual.to_string(),
        },
        value,
    )
}

#[cfg(feature = "file-advanced")]
fn checksum_mismatch(algorithm: &str, value: &Value) -> VldError {
    file_err(
        IssueCode::ChecksumMismatch {
            algorithm: algorithm.to_string(),
        },
        value,
    )
}

fn io_err(msg: impl Into<String>, value: &Value) -> VldError {
    VldError::single_with_value(IssueCode::IoError, msg, value)
}

impl ZFile {
    /// Checks that need the file content (hashes, image dimensions, EXIF).
    fn needs_content_checks(&self) -> bool {
        self.sha256_hex.is_some()
            || self.md5_hex.is_some()
            || self.needs_dimensions()
            || self.require_exif
    }

    fn needs_dimensions(&self) -> bool {
        self.min_width.is_some()
            || self.max_width.is_some()
            || self.min_height.is_some()
            || self.max_height.is_some()
    }

    fn needs_bytes(&self) -> bool {
        self.storage == FileStorage::InMemory
            || !self.allowed_media_types.is_empty()
            || !self.denied_media_types.is_empty()
            || !self.allowed_magic_types.is_empty()
            || !self.denied_magic_types.is_empty()
            || self.needs_content_checks()
    }

    fn check_size(&self, size: u64, value: &Value) -> Result<(), VldError> {
        if let Some(min) = self.min_size.filter(|&m| size < m) {
            return Err(VldError::from_code_with_value(
                IssueCode::TooSmall {
                    origin: SizeOrigin::File,
                    minimum: min.into(),
                    inclusive: true,
                },
                value,
            ));
        }
        if let Some(max) = self.max_size.filter(|&m| size > m) {
            return Err(VldError::from_code_with_value(
                IssueCode::TooBig {
                    origin: SizeOrigin::File,
                    maximum: max.into(),
                    inclusive: true,
                },
                value,
            ));
        }
        Ok(())
    }

    #[cfg(feature = "file-advanced")]
    fn check_dimensions(&self, bytes: &[u8], value: &Value) -> Result<(), VldError> {
        // Reads only the image header; the pixels are never decoded.
        let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes))
            .with_guessed_format()
            .ok()
            .and_then(|r| r.into_dimensions().ok())
            .ok_or_else(|| {
                file_err(
                    IssueCode::InvalidFormat {
                        format: crate::error::FormatKind::Image,
                    },
                    value,
                )
            })?;
        let small = |origin, bound: u32| IssueCode::TooSmall {
            origin,
            minimum: bound.into(),
            inclusive: true,
        };
        let big = |origin, bound: u32| IssueCode::TooBig {
            origin,
            maximum: bound.into(),
            inclusive: true,
        };
        let failure = [
            self.min_width
                .filter(|&m| w < m)
                .map(|m| small(SizeOrigin::ImageWidth, m)),
            self.max_width
                .filter(|&m| w > m)
                .map(|m| big(SizeOrigin::ImageWidth, m)),
            self.min_height
                .filter(|&m| h < m)
                .map(|m| small(SizeOrigin::ImageHeight, m)),
            self.max_height
                .filter(|&m| h > m)
                .map(|m| big(SizeOrigin::ImageHeight, m)),
        ]
        .into_iter()
        .flatten()
        .next();
        match failure {
            Some(code) => Err(file_err(code, value)),
            None => Ok(()),
        }
    }
}

impl VldSchema for ZFile {
    type Output = ValidatedFile;

    fn parse_value(&self, value: &Value) -> Result<ValidatedFile, VldError> {
        let path_str = extract_path(value).map_err(|e| {
            if self.custom_type_error.is_some() {
                crate::primitives::type_error(&self.custom_type_error, "file", value)
            } else {
                e
            }
        })?;
        let mut path = PathBuf::from(path_str);
        if let Some(base) = &self.within_base {
            path = resolve_within(base, &path).ok_or_else(|| outside_base_error(base, value))?;
        }

        if !path.exists() {
            return Err(file_err(IssueCode::PathNotFound, value));
        }
        if !path.is_file() {
            return Err(file_err(IssueCode::PathNotFile, value));
        }

        let extension = path
            .extension()
            .map(|e| e.to_string_lossy().to_ascii_lowercase());
        let ext = extension.as_deref().unwrap_or_default();
        if !self.allowed_extensions.is_empty()
            && !self.allowed_extensions.iter().any(|allowed| allowed == ext)
        {
            return Err(not_allowed(
                FileTypeKind::Extension,
                ext,
                &self.allowed_extensions,
                value,
            ));
        }
        if self.denied_extensions.iter().any(|deny| deny == ext) {
            return Err(denied(FileTypeKind::Extension, ext, value));
        }

        // Size and content come from the same open handle (no stat/read race),
        // and reading never goes past `max_size + 1` bytes.
        let file =
            File::open(&path).map_err(|e| io_err(format!("Failed to open file: {}", e), value))?;
        let mut size = file
            .metadata()
            .map_err(|e| io_err(format!("Failed to read file metadata: {}", e), value))?
            .len();
        self.check_size(size, value)?;

        let loaded_bytes = if self.needs_bytes() {
            let mut buf = Vec::new();
            let limit = self.max_size.map_or(u64::MAX, |m| m.saturating_add(1));
            file.take(limit)
                .read_to_end(&mut buf)
                .map_err(|e| io_err(format!("Failed to read file: {}", e), value))?;
            size = buf.len() as u64;
            self.check_size(size, value)?;
            Some(buf)
        } else {
            None
        };

        let kind = loaded_bytes.as_deref().and_then(infer::get);
        let media_type = kind.map(|k| k.mime_type().to_ascii_lowercase());
        let magic_type = kind.map(|k| k.extension().to_ascii_lowercase());

        if !self.allowed_media_types.is_empty() {
            let mt = media_type.as_deref().ok_or_else(|| {
                file_err(
                    IssueCode::FileTypeUnknown {
                        kind: FileTypeKind::MediaType,
                    },
                    value,
                )
            })?;
            if !self
                .allowed_media_types
                .iter()
                .any(|allowed| media_matches(mt, allowed))
            {
                return Err(not_allowed(
                    FileTypeKind::MediaType,
                    mt,
                    &self.allowed_media_types,
                    value,
                ));
            }
        }
        if let Some(mt) = media_type.as_deref() {
            if self
                .denied_media_types
                .iter()
                .any(|deny| media_matches(mt, deny))
            {
                return Err(denied(FileTypeKind::MediaType, mt, value));
            }
        }
        if !self.allowed_magic_types.is_empty() {
            let kind = magic_type.as_deref().ok_or_else(|| {
                file_err(
                    IssueCode::FileTypeUnknown {
                        kind: FileTypeKind::MagicType,
                    },
                    value,
                )
            })?;
            if !self.allowed_magic_types.iter().any(|a| a == kind) {
                return Err(not_allowed(
                    FileTypeKind::MagicType,
                    kind,
                    &self.allowed_magic_types,
                    value,
                ));
            }
        }
        if let Some(kind) = magic_type.as_deref() {
            if self.denied_magic_types.iter().any(|d| d == kind) {
                return Err(denied(FileTypeKind::MagicType, kind, value));
            }
        }

        #[cfg(feature = "file-advanced")]
        if let (true, Some(bytes)) = (self.needs_content_checks(), loaded_bytes.as_deref()) {
            if let Some(expected) = &self.sha256_hex {
                if &digest_to_hex(Sha256::digest(bytes)) != expected {
                    return Err(checksum_mismatch("SHA-256", value));
                }
            }
            if let Some(expected) = &self.md5_hex {
                if &digest_to_hex(Md5::digest(bytes)) != expected {
                    return Err(checksum_mismatch("MD5", value));
                }
            }
            if self.needs_dimensions() {
                self.check_dimensions(bytes, value)?;
            }
            if self.require_exif {
                exif::Reader::new()
                    .read_from_container(&mut std::io::Cursor::new(bytes))
                    .map_err(|_| file_err(IssueCode::MissingExif, value))?;
            }
        }

        Ok(ValidatedFile {
            path,
            size,
            media_type,
            extension,
            bytes: if self.storage == FileStorage::InMemory {
                loaded_bytes
            } else {
                None
            },
        })
    }
}

#[cfg(feature = "openapi")]
impl crate::openapi::JsonSchema for ZFile {
    fn json_schema(&self) -> serde_json::Value {
        // The input: a path string or `{"path": "..."}`.
        let mut schema = serde_json::json!({
            "anyOf": [
                { "type": "string" },
                {
                    "type": "object",
                    "required": ["path"],
                    "properties": { "path": { "type": "string" } }
                }
            ]
        });
        if let Some(min) = self.min_size {
            schema["x-minFileSize"] = serde_json::json!(min);
        }
        if let Some(max) = self.max_size {
            schema["x-maxFileSize"] = serde_json::json!(max);
        }
        schema
    }
}

#[cfg(feature = "openapi")]
impl crate::openapi::CollectNestedSchemas for ZFile {}