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            .try_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    /// Enables selection and user removal; disabling alone does not revoke
236    /// read rights for an existing selected token.
237    pub enabled: bool,
238    pub configuration: FileConfig,
239    pub revision: u64,
240}
241impl Default for FileProps {
242    fn default() -> Self {
243        Self {
244            label: "Choose file".into(),
245            enabled: true,
246            configuration: FileConfig::default(),
247            revision: 0,
248        }
249    }
250}
251impl FileProps {
252    pub fn validate(&self) -> Result<(), Error> {
253        self.configuration.validate()?;
254        self.validate_label()
255    }
256    pub(crate) fn validate_label(&self) -> Result<(), Error> {
257        if self.label.len() > 4096
258            || self.label.contains(['\r', '\0'])
259            || self.label.trim().is_empty()
260        {
261            return Err(Error::InvalidProps(
262                "file button requires a nonempty canonical label of at most 4096 bytes",
263            ));
264        }
265        Ok(())
266    }
267    pub fn validate_update(&self, previous: &Self) -> Result<(), Error> {
268        self.validate()?;
269        if self.revision < previous.revision
270            || self.revision == previous.revision && self.configuration != previous.configuration
271        {
272            return Err(Error::InvalidProps(
273                "file configuration changes must advance their revision",
274            ));
275        }
276        Ok(())
277    }
278}
279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280pub enum FileRejection {
281    Count,
282    Type,
283    Bytes,
284    Metadata,
285    Busy,
286    Unavailable,
287    Failed,
288}
289#[derive(Clone, Debug, PartialEq, Eq)]
290pub enum FileOutcome {
291    Selected(Vec<FileInfo>),
292    Cancelled,
293    Rejected(FileRejection),
294}
295impl FileOutcome {
296    pub fn validate(&self) -> Result<(), Error> {
297        if let Self::Selected(files) = self {
298            if files.is_empty() || files.len() > MAX_FILE_COUNT {
299                return Err(Error::InvalidEvent("selected file event exceeds 32 files"));
300            }
301            let mut metadata = 0usize;
302            let mut total = 0u64;
303            for (index, file) in files.iter().enumerate() {
304                file.validate()?;
305                if let Some(first) = files.first()
306                    && (file.token.document != first.token.document
307                        || file.token.node != first.token.node
308                        || file.token.revision != first.token.revision)
309                {
310                    return Err(Error::InvalidEvent(
311                        "selected references require the same document, node and revision",
312                    ));
313                }
314                metadata = metadata
315                    .checked_add(file.name.len() + file.media_type.len())
316                    .ok_or(Error::InvalidEvent("file metadata overflow"))?;
317                total = total
318                    .checked_add(file.size)
319                    .ok_or(Error::InvalidEvent("file sizes overflow"))?;
320                if metadata > MAX_FILE_METADATA_BYTES
321                    || total > MAX_FILE_BYTES
322                    || files[..index].iter().any(|other| other.token == file.token)
323                {
324                    return Err(Error::InvalidEvent(
325                        "selected file event exceeds its unique metadata/byte domain",
326                    ));
327                }
328            }
329        }
330        Ok(())
331    }
332}
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub struct FileRead {
335    pub file: FileToken,
336    pub offset: u64,
337    pub length: u32,
338}
339impl FileRead {
340    pub fn validate(self) -> Result<(), Error> {
341        self.file.validate()?;
342        if self.length > MAX_FILE_CHUNK_BYTES
343            || self
344                .offset
345                .checked_add(u64::from(self.length))
346                .is_none_or(|end| end > MAX_FILE_BYTES)
347        {
348            Err(Error::InvalidProps(
349                "file reads require a finite range of at most 65536 bytes",
350            ))
351        } else {
352            Ok(())
353        }
354    }
355    pub fn validate_file(self, file: &FileInfo) -> Result<(), Error> {
356        self.validate()?;
357        file.validate()?;
358        if self.file != file.token || self.offset + u64::from(self.length) > file.size {
359            Err(Error::InvalidProps(
360                "file read exceeds its live selected reference or size",
361            ))
362        } else {
363            Ok(())
364        }
365    }
366}
367#[derive(Clone, Copy, Debug, PartialEq, Eq)]
368pub struct FileCapabilities {
369    pub document: FileDocumentId,
370    pub picker: bool,
371    pub drop: bool,
372    pub read: bool,
373    pub preview: bool,
374}
375#[derive(Clone, Copy, Debug, PartialEq, Eq)]
376pub enum FileOrigin {
377    Picker,
378    Drop,
379    /// Trusted adoption of a pre-WASM selection into a fresh consumer lifetime.
380    Adopted,
381}
382#[derive(Clone, Debug, PartialEq, Eq)]
383pub struct FileEvent {
384    pub document: FileDocumentId,
385    pub revision: u64,
386    pub request: Option<u64>,
387    pub batch: u64,
388    pub origin: FileOrigin,
389    pub outcome: FileOutcome,
390}
391impl FileEvent {
392    pub fn validate(&self) -> Result<(), Error> {
393        if self.batch == 0
394            || match self.origin {
395                FileOrigin::Picker => self.request.is_none_or(|request| request == 0),
396                FileOrigin::Drop | FileOrigin::Adopted => self.request.is_some(),
397            }
398        {
399            return Err(Error::InvalidEvent(
400                "file observations require a positive batch and origin-specific request",
401            ));
402        }
403        self.outcome.validate()?;
404        if let FileOutcome::Selected(files) = &self.outcome
405            && files.iter().any(|file| {
406                file.token.document != self.document || file.token.revision != self.revision
407            })
408        {
409            return Err(Error::InvalidEvent(
410                "file observation references must match document and revision",
411            ));
412        }
413        Ok(())
414    }
415    pub fn validate_node(&self, node: NodeId, configuration: &FileProps) -> Result<(), Error> {
416        self.validate()?;
417        if self.revision > configuration.revision {
418            return Err(Error::InvalidEvent(
419                "file observation exceeds current configuration revision",
420            ));
421        }
422        if let FileOutcome::Selected(files) = &self.outcome
423            && files.iter().any(|file| file.token.node != node)
424        {
425            return Err(Error::InvalidEvent(
426                "file observation references a different picker node",
427            ));
428        }
429        // A retired declaration may have had different filters/drop policy.
430        // Validate its finite payload and identity, then let admission discard it.
431        if self.revision < configuration.revision {
432            return Ok(());
433        }
434        if self.origin == FileOrigin::Drop && !configuration.configuration.drop {
435            return Err(Error::InvalidEvent("file drop was not enabled"));
436        }
437        if let FileOutcome::Selected(files) = &self.outcome {
438            configuration.configuration.validate_files(files)?;
439        }
440        Ok(())
441    }
442}
443#[derive(Clone, Debug, PartialEq, Eq)]
444pub struct FilePreview {
445    pub image: FileImageInfo,
446    pub file: FileToken,
447    pub source: String,
448}
449impl FilePreview {
450    /// Exact document-local resource address used by native file services.
451    /// The address grants no ambient path or filesystem access.
452    pub fn native_source(file: FileToken) -> String {
453        format!(
454            "file-preview://document-{}/{}/{}/{}/{}/{}",
455            file.document.value(),
456            file.node.runtime().value(),
457            file.node.slot(),
458            file.node.generation(),
459            file.revision,
460            file.serial
461        )
462    }
463    pub fn validate(&self) -> Result<(), Error> {
464        self.file.validate()?;
465        self.image
466            .validate(FilePreviewLimits::default())
467            .map_err(|_| Error::InvalidProps("file preview image exceeds pixel domain"))?;
468        if self.source.len() > 2048
469            || !(self.source.starts_with("blob:") || self.source == Self::native_source(self.file))
470            || self.source.contains(['\r', '\n', '\0'])
471        {
472            Err(Error::InvalidProps(
473                "file preview requires a bounded document-owned resource URI",
474            ))
475        } else {
476            Ok(())
477        }
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484    use crate::{NodeIds, RuntimeId};
485    fn reference() -> FileInfo {
486        let mut ids = NodeIds::new(RuntimeId::new());
487        FileInfo {
488            token: FileToken {
489                document: FileDocumentId::new().unwrap(),
490                node: ids.allocate(),
491                revision: 3,
492                serial: 1,
493            },
494            name: "bounded.txt".into(),
495            media_type: "text/plain".into(),
496            size: 4,
497        }
498    }
499    #[test]
500    fn document_identity_does_not_alias_same_runtime_consumers_and_never_wraps() {
501        let a = FileDocumentId::new().unwrap();
502        let b = FileDocumentId::new().unwrap();
503        assert_ne!(a, b);
504        let counter = AtomicU64::new(u64::MAX - 1);
505        assert_eq!(
506            FileDocumentId::allocate(&counter).unwrap().value(),
507            u64::MAX - 1
508        );
509        assert!(FileDocumentId::allocate(&counter).is_err());
510        assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
511    }
512    #[test]
513    fn independent_filter_count_string_and_file_size_budgets() {
514        let mut c = FileConfig::default();
515        c.validate().unwrap();
516        c.max_files = 0;
517        assert!(c.validate().is_err());
518        c.max_files = 2;
519        assert!(c.validate().is_err());
520        c.multiple = true;
521        c.max_files = 32;
522        c.validate().unwrap();
523        c.max_files = 33;
524        assert!(c.validate().is_err());
525        c.max_files = 32;
526        c.filters = vec![FileFilter::Mime("text/plain".into()); 33];
527        assert!(c.validate().is_err());
528        c.filters = vec![FileFilter::Mime(format!("application/{}", "x".repeat(110))); 32];
529        assert!(c.validate().is_err());
530        c.filters = vec![FileFilter::Mime("text/*".into())];
531        c.validate_files(&[reference()]).unwrap();
532        c.max_file_bytes = 3;
533        assert!(c.validate_files(&[reference()]).is_err());
534        c.max_file_bytes = 4;
535        c.max_total_bytes = 3;
536        assert!(c.validate_files(&[reference()]).is_err());
537        for value in [
538            "",
539            "TEXT/plain",
540            "text/**",
541            "text/plain; charset=utf8",
542            "text/",
543            "*/plain",
544        ] {
545            assert!(FileFilter::Mime(value.into()).validate().is_err())
546        }
547        for value in ["txt", ".TXT", ".a/b"] {
548            assert!(FileFilter::Extension(value.into()).validate().is_err())
549        }
550    }
551    #[test]
552    fn names_mime_metadata_total_unique_and_origin_domains() {
553        let original = reference();
554        let mut item = original.clone();
555        item.name = "x".repeat(1025);
556        assert!(item.validate().is_err());
557        item = original.clone();
558        item.name = "nul\0".into();
559        assert!(item.validate().is_err());
560        item = original.clone();
561        item.media_type = "X/upper".into();
562        assert!(item.validate().is_err());
563        item = original.clone();
564        item.size = MAX_FILE_BYTES + 1;
565        assert!(item.validate().is_err());
566        assert!(FileOutcome::Selected(vec![]).validate().is_err());
567        assert!(
568            FileOutcome::Selected(vec![original.clone(), original.clone()])
569                .validate()
570                .is_err()
571        );
572        let mut other = original.clone();
573        other.token.serial = 2;
574        other.token.document = FileDocumentId::new().unwrap();
575        assert!(
576            FileOutcome::Selected(vec![original.clone(), other])
577                .validate()
578                .is_err()
579        );
580        let files = (1..=32)
581            .map(|serial| {
582                let mut value = original.clone();
583                value.token.serial = serial;
584                value.name = "x".repeat(1024);
585                value
586            })
587            .collect::<Vec<_>>();
588        assert!(FileOutcome::Selected(files).validate().is_err());
589    }
590    #[test]
591    fn chunk_ranges_are_checked_before_bytes_or_platform_work() {
592        let file = reference();
593        FileRead {
594            file: file.token,
595            offset: 4,
596            length: 0,
597        }
598        .validate_file(&file)
599        .unwrap();
600        for (offset, length) in [(0, 65537), (u64::MAX, 1), (5, 0), (3, 2)] {
601            assert!(
602                FileRead {
603                    file: file.token,
604                    offset,
605                    length
606                }
607                .validate_file(&file)
608                .is_err()
609            )
610        }
611        let mut foreign = file.clone();
612        foreign.token.document = FileDocumentId::new().unwrap();
613        assert!(
614            FileRead {
615                file: file.token,
616                offset: 0,
617                length: 4
618            }
619            .validate_file(&foreign)
620            .is_err()
621        );
622    }
623    #[test]
624    fn request_origin_config_revision_and_changed_declaration_are_independent() {
625        let file = reference();
626        let mut props = FileProps {
627            revision: 3,
628            ..Default::default()
629        };
630        let event = FileEvent {
631            document: file.token.document,
632            revision: 3,
633            request: Some(1),
634            batch: 1,
635            origin: FileOrigin::Picker,
636            outcome: FileOutcome::Selected(vec![file.clone()]),
637        };
638        event.validate_node(file.token.node, &props).unwrap();
639        let mut invalid = event.clone();
640        invalid.origin = FileOrigin::Drop;
641        invalid.request = None;
642        assert!(invalid.validate_node(file.token.node, &props).is_err());
643        props.configuration.drop = true;
644        invalid.validate_node(file.token.node, &props).unwrap();
645        invalid.revision = 4;
646        assert!(invalid.validate_node(file.token.node, &props).is_err());
647        let mut next = props.clone();
648        next.configuration.max_file_bytes = 1;
649        assert!(next.validate_update(&props).is_err());
650        next.revision = 4;
651        next.validate_update(&props).unwrap();
652    }
653}
654
655#[path = "file_state.rs"]
656pub(crate) mod state;
657
658/// One exact bounded read response, never an ambient filesystem path.
659#[derive(Clone, Debug, PartialEq, Eq)]
660pub struct FileChunk {
661    pub file: FileToken,
662    pub offset: u64,
663    pub bytes: Vec<u8>,
664}
665impl FileChunk {
666    pub fn validate_read(&self, request: FileRead) -> Result<(), Error> {
667        request.validate()?;
668        if self.file != request.file
669            || self.offset != request.offset
670            || self.bytes.len() != request.length as usize
671        {
672            return Err(Error::InvalidResponse(
673                "file response does not match its exact bounded read",
674            ));
675        }
676        Ok(())
677    }
678}