Skip to main content

glory_render/
files.rs

1//! Finite file-picker declarations and opaque document-owned read references.
2//! A token is never a filename, URL, filesystem path, browser object or lease.
3use crate::{Error, NodeId};
4#[path = "file_preview.rs"]
5mod preview;
6pub use preview::*;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9pub const MAX_FILE_COUNT: usize = 32;
10pub const MAX_FILE_FILTERS: usize = 32;
11pub const MAX_FILE_FILTER_BYTES: usize = 2048;
12pub const MAX_FILE_NAME_BYTES: usize = 1024;
13pub const MAX_FILE_MIME_BYTES: usize = 127;
14pub const MAX_FILE_METADATA_BYTES: usize = 32768;
15pub const MAX_FILE_BYTES: u64 = 1024 * 1024 * 1024;
16pub const MAX_FILE_CHUNK_BYTES: u32 = 65536;
17pub const MAX_FILE_READS: usize = 4;
18
19/// Distinguishes independent consumers even when they share one RuntimeId.
20#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub struct FileDocumentId(u64);
22impl FileDocumentId {
23    pub fn new() -> Result<Self, Error> {
24        static NEXT: AtomicU64 = AtomicU64::new(1);
25        Self::allocate(&NEXT)
26    }
27    fn allocate(counter: &AtomicU64) -> Result<Self, Error> {
28        counter
29            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
30                value.checked_add(1)
31            })
32            .map(Self)
33            .map_err(|_| Error::InvalidProps("file document identity exhausted"))
34    }
35    pub fn value(self) -> u64 {
36        self.0
37    }
38}
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub struct FileToken {
41    pub document: FileDocumentId,
42    pub node: NodeId,
43    pub revision: u64,
44    pub serial: u64,
45}
46impl FileToken {
47    pub fn validate(self) -> Result<(), Error> {
48        if self.serial == 0 {
49            Err(Error::InvalidProps(
50                "file token requires a positive document-local serial",
51            ))
52        } else {
53            Ok(())
54        }
55    }
56}
57#[derive(Clone, Debug, PartialEq, Eq)]
58pub struct FileInfo {
59    pub token: FileToken,
60    /// Display metadata only. Never interpret or reopen this string as a path.
61    pub name: String,
62    pub media_type: String,
63    pub size: u64,
64}
65fn mime(value: &str, wildcard: bool) -> bool {
66    if value.len() > MAX_FILE_MIME_BYTES {
67        return false;
68    }
69    let Some((major, minor)) = value.split_once('/') else {
70        return false;
71    };
72    let token = |value: &str| {
73        !value.is_empty()
74            && value
75                .bytes()
76                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"!#$&-^_.+".contains(&b))
77    };
78    token(major) && (token(minor) || wildcard && minor == "*")
79}
80impl FileInfo {
81    pub fn validate(&self) -> Result<(), Error> {
82        self.token.validate()?;
83        if self.name.is_empty()
84            || self.name.len() > MAX_FILE_NAME_BYTES
85            || self.name.contains(['\r', '\0'])
86            || (!self.media_type.is_empty() && !mime(&self.media_type, false))
87            || self.size > MAX_FILE_BYTES
88        {
89            Err(Error::InvalidProps(
90                "file metadata exceeds its canonical name, MIME or byte domain",
91            ))
92        } else {
93            Ok(())
94        }
95    }
96}
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub enum FileFilter {
99    Mime(String),
100    Extension(String),
101}
102impl FileFilter {
103    pub fn validate(&self) -> Result<(), Error> {
104        let valid = match self {
105            Self::Mime(value) => mime(value, true),
106            Self::Extension(value) => {
107                value.len() >= 2
108                    && value.len() <= 32
109                    && value.starts_with('.')
110                    && value.bytes().skip(1).all(|b| {
111                        b.is_ascii_lowercase() || b.is_ascii_digit() || b".-_".contains(&b)
112                    })
113            }
114        };
115        if valid {
116            Ok(())
117        } else {
118            Err(Error::InvalidProps(
119                "file filter requires a lowercase MIME, type/*, or extension",
120            ))
121        }
122    }
123    pub fn text(&self) -> &str {
124        match self {
125            Self::Mime(value) | Self::Extension(value) => value,
126        }
127    }
128    pub fn matches(&self, file: &FileInfo) -> bool {
129        match self {
130            Self::Extension(extension) => file.name.to_ascii_lowercase().ends_with(extension),
131            Self::Mime(value) => {
132                if let Some(prefix) = value.strip_suffix('*') {
133                    file.media_type.starts_with(prefix)
134                } else {
135                    file.media_type == *value
136                }
137            }
138        }
139    }
140}
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct FileConfig {
143    pub multiple: bool,
144    pub drop: bool,
145    pub preview: Option<FilePreviewLimits>,
146    pub filters: Vec<FileFilter>,
147    pub max_files: usize,
148    pub max_file_bytes: u64,
149    pub max_total_bytes: u64,
150}
151impl Default for FileConfig {
152    fn default() -> Self {
153        Self {
154            multiple: false,
155            drop: false,
156            preview: None,
157            filters: Vec::new(),
158            max_files: 1,
159            max_file_bytes: 16 * 1024 * 1024,
160            max_total_bytes: 32 * 1024 * 1024,
161        }
162    }
163}
164impl FileConfig {
165    pub fn validate(&self) -> Result<(), Error> {
166        if !(1..=MAX_FILE_COUNT).contains(&self.max_files)
167            || !self.multiple && self.max_files != 1
168            || self.max_file_bytes > MAX_FILE_BYTES
169            || self.max_total_bytes > MAX_FILE_BYTES
170            || self.filters.len() > MAX_FILE_FILTERS
171        {
172            return Err(Error::InvalidProps(
173                "file picker configuration exceeds count, size or filter domain",
174            ));
175        }
176        if let Some(preview) = self.preview {
177            preview
178                .validate()
179                .map_err(|_| Error::InvalidProps("invalid finite file preview budget"))?;
180        }
181        let mut bytes = 0usize;
182        for filter in &self.filters {
183            filter.validate()?;
184            bytes = bytes
185                .checked_add(filter.text().len())
186                .ok_or(Error::InvalidProps("file filter size overflow"))?;
187        }
188        if bytes > MAX_FILE_FILTER_BYTES {
189            return Err(Error::InvalidProps("file filter strings exceed 2048 bytes"));
190        }
191        Ok(())
192    }
193    pub fn validate_files(&self, files: &[FileInfo]) -> Result<(), Error> {
194        self.validate()?;
195        if files.len() > self.max_files {
196            return Err(Error::InvalidProps(
197                "selected file count exceeds configuration",
198            ));
199        }
200        let mut total = 0u64;
201        let mut metadata = 0usize;
202        for (index, file) in files.iter().enumerate() {
203            file.validate()?;
204            if file.size > self.max_file_bytes {
205                return Err(Error::InvalidProps(
206                    "selected file exceeds per-file byte budget",
207                ));
208            }
209            total = total
210                .checked_add(file.size)
211                .ok_or(Error::InvalidProps("selected file sizes overflow"))?;
212            metadata = metadata
213                .checked_add(file.name.len() + file.media_type.len())
214                .ok_or(Error::InvalidProps("selected file metadata size overflow"))?;
215            if total > self.max_total_bytes || metadata > MAX_FILE_METADATA_BYTES {
216                return Err(Error::InvalidProps(
217                    "selected file total exceeds byte or metadata budget",
218                ));
219            }
220            if !self.filters.is_empty() && !self.filters.iter().any(|filter| filter.matches(file)) {
221                return Err(Error::InvalidProps(
222                    "selected file does not match a declared filter",
223                ));
224            }
225            if files[..index].iter().any(|other| other.token == file.token) {
226                return Err(Error::InvalidProps("selected file tokens must be unique"));
227            }
228        }
229        Ok(())
230    }
231}
232#[derive(Clone, Debug, PartialEq, Eq)]
233pub struct FileProps {
234    pub label: String,
235    pub enabled: bool,
236    pub configuration: FileConfig,
237    pub revision: u64,
238}
239impl Default for FileProps {
240    fn default() -> Self {
241        Self {
242            label: "Choose file".into(),
243            enabled: true,
244            configuration: FileConfig::default(),
245            revision: 0,
246        }
247    }
248}
249impl FileProps {
250    pub fn validate(&self) -> Result<(), Error> {
251        self.configuration.validate()?;
252        self.validate_label()
253    }
254    pub(crate) fn validate_label(&self) -> Result<(), Error> {
255        if self.label.len() > 4096
256            || self.label.contains(['\r', '\0'])
257            || self.label.trim().is_empty()
258        {
259            return Err(Error::InvalidProps(
260                "file button requires a nonempty canonical label of at most 4096 bytes",
261            ));
262        }
263        Ok(())
264    }
265    pub fn validate_update(&self, previous: &Self) -> Result<(), Error> {
266        self.validate()?;
267        if self.revision < previous.revision
268            || self.revision == previous.revision && self.configuration != previous.configuration
269        {
270            return Err(Error::InvalidProps(
271                "file configuration changes must advance their revision",
272            ));
273        }
274        Ok(())
275    }
276}
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum FileRejection {
279    Count,
280    Type,
281    Bytes,
282    Metadata,
283    Busy,
284    Unavailable,
285    Failed,
286}
287#[derive(Clone, Debug, PartialEq, Eq)]
288pub enum FileOutcome {
289    Selected(Vec<FileInfo>),
290    Cancelled,
291    Rejected(FileRejection),
292}
293impl FileOutcome {
294    pub fn validate(&self) -> Result<(), Error> {
295        if let Self::Selected(files) = self {
296            if files.is_empty() || files.len() > MAX_FILE_COUNT {
297                return Err(Error::InvalidEvent("selected file event exceeds 32 files"));
298            }
299            let mut metadata = 0usize;
300            let mut total = 0u64;
301            for (index, file) in files.iter().enumerate() {
302                file.validate()?;
303                if let Some(first) = files.first()
304                    && (file.token.document != first.token.document
305                        || file.token.node != first.token.node
306                        || file.token.revision != first.token.revision)
307                {
308                    return Err(Error::InvalidEvent(
309                        "selected references require the same document, node and revision",
310                    ));
311                }
312                metadata = metadata
313                    .checked_add(file.name.len() + file.media_type.len())
314                    .ok_or(Error::InvalidEvent("file metadata overflow"))?;
315                total = total
316                    .checked_add(file.size)
317                    .ok_or(Error::InvalidEvent("file sizes overflow"))?;
318                if metadata > MAX_FILE_METADATA_BYTES
319                    || total > MAX_FILE_BYTES
320                    || files[..index].iter().any(|other| other.token == file.token)
321                {
322                    return Err(Error::InvalidEvent(
323                        "selected file event exceeds its unique metadata/byte domain",
324                    ));
325                }
326            }
327        }
328        Ok(())
329    }
330}
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub struct FileRead {
333    pub file: FileToken,
334    pub offset: u64,
335    pub length: u32,
336}
337impl FileRead {
338    pub fn validate(self) -> Result<(), Error> {
339        self.file.validate()?;
340        if self.length > MAX_FILE_CHUNK_BYTES
341            || self
342                .offset
343                .checked_add(u64::from(self.length))
344                .is_none_or(|end| end > MAX_FILE_BYTES)
345        {
346            Err(Error::InvalidProps(
347                "file reads require a finite range of at most 65536 bytes",
348            ))
349        } else {
350            Ok(())
351        }
352    }
353    pub fn validate_file(self, file: &FileInfo) -> Result<(), Error> {
354        self.validate()?;
355        file.validate()?;
356        if self.file != file.token || self.offset + u64::from(self.length) > file.size {
357            Err(Error::InvalidProps(
358                "file read exceeds its live selected reference or size",
359            ))
360        } else {
361            Ok(())
362        }
363    }
364}
365#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366pub struct FileCapabilities {
367    pub document: FileDocumentId,
368    pub picker: bool,
369    pub drop: bool,
370    pub read: bool,
371    pub preview: bool,
372}
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374pub enum FileOrigin {
375    Picker,
376    Drop,
377    /// Trusted adoption of a pre-WASM selection into a fresh consumer lifetime.
378    Adopted,
379}
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub struct FileEvent {
382    pub document: FileDocumentId,
383    pub revision: u64,
384    pub request: Option<u64>,
385    pub batch: u64,
386    pub origin: FileOrigin,
387    pub outcome: FileOutcome,
388}
389impl FileEvent {
390    pub fn validate(&self) -> Result<(), Error> {
391        if self.batch == 0
392            || match self.origin {
393                FileOrigin::Picker => self.request.is_none_or(|request| request == 0),
394                FileOrigin::Drop | FileOrigin::Adopted => self.request.is_some(),
395            }
396        {
397            return Err(Error::InvalidEvent(
398                "file observations require a positive batch and origin-specific request",
399            ));
400        }
401        self.outcome.validate()?;
402        if let FileOutcome::Selected(files) = &self.outcome
403            && files.iter().any(|file| {
404                file.token.document != self.document || file.token.revision != self.revision
405            })
406        {
407            return Err(Error::InvalidEvent(
408                "file observation references must match document and revision",
409            ));
410        }
411        Ok(())
412    }
413    pub fn validate_node(&self, node: NodeId, configuration: &FileProps) -> Result<(), Error> {
414        self.validate()?;
415        if self.revision > configuration.revision {
416            return Err(Error::InvalidEvent(
417                "file observation exceeds current configuration revision",
418            ));
419        }
420        if let FileOutcome::Selected(files) = &self.outcome
421            && files.iter().any(|file| file.token.node != node)
422        {
423            return Err(Error::InvalidEvent(
424                "file observation references a different picker node",
425            ));
426        }
427        // A retired declaration may have had different filters/drop policy.
428        // Validate its finite payload and identity, then let admission discard it.
429        if self.revision < configuration.revision {
430            return Ok(());
431        }
432        if self.origin == FileOrigin::Drop && !configuration.configuration.drop {
433            return Err(Error::InvalidEvent("file drop was not enabled"));
434        }
435        if let FileOutcome::Selected(files) = &self.outcome {
436            configuration.configuration.validate_files(files)?;
437        }
438        Ok(())
439    }
440}
441#[derive(Clone, Debug, PartialEq, Eq)]
442pub struct FilePreview {
443    pub image: FileImageInfo,
444    pub file: FileToken,
445    pub source: String,
446}
447impl FilePreview {
448    /// Exact document-local resource address used by native file services.
449    /// The address grants no ambient path or filesystem access.
450    pub fn native_source(file: FileToken) -> String {
451        format!(
452            "file-preview://document-{}/{}/{}/{}/{}/{}",
453            file.document.value(),
454            file.node.runtime().value(),
455            file.node.slot(),
456            file.node.generation(),
457            file.revision,
458            file.serial
459        )
460    }
461    pub fn validate(&self) -> Result<(), Error> {
462        self.file.validate()?;
463        self.image
464            .validate(FilePreviewLimits::default())
465            .map_err(|_| Error::InvalidProps("file preview image exceeds pixel domain"))?;
466        if self.source.len() > 2048
467            || !(self.source.starts_with("blob:") || self.source == Self::native_source(self.file))
468            || self.source.contains(['\r', '\n', '\0'])
469        {
470            Err(Error::InvalidProps(
471                "file preview requires a bounded document-owned resource URI",
472            ))
473        } else {
474            Ok(())
475        }
476    }
477}
478
479#[cfg(test)]
480mod tests {
481    use super::*;
482    use crate::{NodeIds, RuntimeId};
483    fn reference() -> FileInfo {
484        let mut ids = NodeIds::new(RuntimeId::new());
485        FileInfo {
486            token: FileToken {
487                document: FileDocumentId::new().unwrap(),
488                node: ids.allocate(),
489                revision: 3,
490                serial: 1,
491            },
492            name: "bounded.txt".into(),
493            media_type: "text/plain".into(),
494            size: 4,
495        }
496    }
497    #[test]
498    fn document_identity_does_not_alias_same_runtime_consumers_and_never_wraps() {
499        let a = FileDocumentId::new().unwrap();
500        let b = FileDocumentId::new().unwrap();
501        assert_ne!(a, b);
502        let counter = AtomicU64::new(u64::MAX - 1);
503        assert_eq!(
504            FileDocumentId::allocate(&counter).unwrap().value(),
505            u64::MAX - 1
506        );
507        assert!(FileDocumentId::allocate(&counter).is_err());
508        assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
509    }
510    #[test]
511    fn independent_filter_count_string_and_file_size_budgets() {
512        let mut c = FileConfig::default();
513        c.validate().unwrap();
514        c.max_files = 0;
515        assert!(c.validate().is_err());
516        c.max_files = 2;
517        assert!(c.validate().is_err());
518        c.multiple = true;
519        c.max_files = 32;
520        c.validate().unwrap();
521        c.max_files = 33;
522        assert!(c.validate().is_err());
523        c.max_files = 32;
524        c.filters = vec![FileFilter::Mime("text/plain".into()); 33];
525        assert!(c.validate().is_err());
526        c.filters = vec![FileFilter::Mime(format!("application/{}", "x".repeat(110))); 32];
527        assert!(c.validate().is_err());
528        c.filters = vec![FileFilter::Mime("text/*".into())];
529        c.validate_files(&[reference()]).unwrap();
530        c.max_file_bytes = 3;
531        assert!(c.validate_files(&[reference()]).is_err());
532        c.max_file_bytes = 4;
533        c.max_total_bytes = 3;
534        assert!(c.validate_files(&[reference()]).is_err());
535        for value in [
536            "",
537            "TEXT/plain",
538            "text/**",
539            "text/plain; charset=utf8",
540            "text/",
541            "*/plain",
542        ] {
543            assert!(FileFilter::Mime(value.into()).validate().is_err())
544        }
545        for value in ["txt", ".TXT", ".a/b"] {
546            assert!(FileFilter::Extension(value.into()).validate().is_err())
547        }
548    }
549    #[test]
550    fn names_mime_metadata_total_unique_and_origin_domains() {
551        let original = reference();
552        let mut item = original.clone();
553        item.name = "x".repeat(1025);
554        assert!(item.validate().is_err());
555        item = original.clone();
556        item.name = "nul\0".into();
557        assert!(item.validate().is_err());
558        item = original.clone();
559        item.media_type = "X/upper".into();
560        assert!(item.validate().is_err());
561        item = original.clone();
562        item.size = MAX_FILE_BYTES + 1;
563        assert!(item.validate().is_err());
564        assert!(FileOutcome::Selected(vec![]).validate().is_err());
565        assert!(
566            FileOutcome::Selected(vec![original.clone(), original.clone()])
567                .validate()
568                .is_err()
569        );
570        let mut other = original.clone();
571        other.token.serial = 2;
572        other.token.document = FileDocumentId::new().unwrap();
573        assert!(
574            FileOutcome::Selected(vec![original.clone(), other])
575                .validate()
576                .is_err()
577        );
578        let files = (1..=32)
579            .map(|serial| {
580                let mut value = original.clone();
581                value.token.serial = serial;
582                value.name = "x".repeat(1024);
583                value
584            })
585            .collect::<Vec<_>>();
586        assert!(FileOutcome::Selected(files).validate().is_err());
587    }
588    #[test]
589    fn chunk_ranges_are_checked_before_bytes_or_platform_work() {
590        let file = reference();
591        FileRead {
592            file: file.token,
593            offset: 4,
594            length: 0,
595        }
596        .validate_file(&file)
597        .unwrap();
598        for (offset, length) in [(0, 65537), (u64::MAX, 1), (5, 0), (3, 2)] {
599            assert!(
600                FileRead {
601                    file: file.token,
602                    offset,
603                    length
604                }
605                .validate_file(&file)
606                .is_err()
607            )
608        }
609        let mut foreign = file.clone();
610        foreign.token.document = FileDocumentId::new().unwrap();
611        assert!(
612            FileRead {
613                file: file.token,
614                offset: 0,
615                length: 4
616            }
617            .validate_file(&foreign)
618            .is_err()
619        );
620    }
621    #[test]
622    fn request_origin_config_revision_and_changed_declaration_are_independent() {
623        let file = reference();
624        let mut props = FileProps {
625            revision: 3,
626            ..Default::default()
627        };
628        let event = FileEvent {
629            document: file.token.document,
630            revision: 3,
631            request: Some(1),
632            batch: 1,
633            origin: FileOrigin::Picker,
634            outcome: FileOutcome::Selected(vec![file.clone()]),
635        };
636        event.validate_node(file.token.node, &props).unwrap();
637        let mut invalid = event.clone();
638        invalid.origin = FileOrigin::Drop;
639        invalid.request = None;
640        assert!(invalid.validate_node(file.token.node, &props).is_err());
641        props.configuration.drop = true;
642        invalid.validate_node(file.token.node, &props).unwrap();
643        invalid.revision = 4;
644        assert!(invalid.validate_node(file.token.node, &props).is_err());
645        let mut next = props.clone();
646        next.configuration.max_file_bytes = 1;
647        assert!(next.validate_update(&props).is_err());
648        next.revision = 4;
649        next.validate_update(&props).unwrap();
650    }
651}
652
653#[path = "file_state.rs"]
654pub(crate) mod state;
655
656/// One exact bounded read response, never an ambient filesystem path.
657#[derive(Clone, Debug, PartialEq, Eq)]
658pub struct FileChunk {
659    pub file: FileToken,
660    pub offset: u64,
661    pub bytes: Vec<u8>,
662}
663impl FileChunk {
664    pub fn validate_read(&self, request: FileRead) -> Result<(), Error> {
665        request.validate()?;
666        if self.file != request.file
667            || self.offset != request.offset
668            || self.bytes.len() != request.length as usize
669        {
670            return Err(Error::InvalidResponse(
671                "file response does not match its exact bounded read",
672            ));
673        }
674        Ok(())
675    }
676}