Skip to main content

nitr_std/validate/
file.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! `nitr.File`: a validated upload. The bytes live in a temporary file the
7//! server spooled; Lua holds a handle with what detection learned and can
8//! keep the file (`save`), read a small one (`text`), hash it, or drop it.
9//! A file neither saved nor discarded is removed when the handle goes.
10
11use std::future::Future;
12use std::path::PathBuf;
13use std::pin::Pin;
14use std::sync::{Arc, Mutex};
15
16use mlua::{ExternalResult as _, UserData, UserDataFields, UserDataMethods};
17
18use super::media::{self, Detection};
19
20/// Resolves a Lua-supplied relative path to the file `save` may rename
21/// the temporary to — the server's containment rule, injected so this
22/// module knows nothing about upload roots.
23pub type SaveResolver = Arc<
24    dyn Fn(String) -> Pin<Box<dyn Future<Output = mlua::Result<PathBuf>> + Send>> + Send + Sync,
25>;
26
27/// What the spooler learned about an upload.
28#[derive(Debug, Clone)]
29pub struct FileInfo {
30    /// The client's file name, raw.
31    pub filename: Option<String>,
32    /// The name reduced to one safe path segment.
33    pub safe_filename: Option<String>,
34    /// The lowercase last suffix of the safe name, without the dot.
35    pub extension: Option<String>,
36    /// The `Content-Type` the client declared for the part.
37    pub declared_type: Option<String>,
38    /// What the first bytes said.
39    pub detected: Detection,
40    /// Whether the declared text subtype's structure was present.
41    pub text_subtype_ok: bool,
42    /// Bytes received.
43    pub size: u64,
44    /// The most bytes the spool stores: the rule's `max_bytes` capped by
45    /// `[limits] max_file_bytes`. A larger `size` is a file cut short.
46    pub cap: u64,
47    /// Image dimensions when the header carried them.
48    pub width: Option<u32>,
49    /// See `width`.
50    pub height: Option<u32>,
51    /// Whether every byte was valid UTF-8 (`None` when not checked).
52    pub utf8: Option<bool>,
53}
54
55impl FileInfo {
56    /// The media type this file is treated as: the detected type when
57    /// there is one; for text, the declared subtype when it is a text type
58    /// whose structure matched, else `text/plain`; otherwise the declared
59    /// header only when nothing in the table would have detected it.
60    pub fn effective_type(&self) -> &str {
61        match self.detected {
62            Detection::Detected(media) => media.name,
63            Detection::Executable => media::EXECUTABLE_TYPE,
64            Detection::Text => match self.declared_type.as_deref() {
65                Some(declared)
66                    if media::lookup(declared).is_some_and(|m| m.tier == media::Tier::Text)
67                        && self.text_subtype_ok =>
68                {
69                    declared
70                }
71                _ => "text/plain",
72            },
73            Detection::Unknown => match self.declared_type.as_deref() {
74                Some(declared)
75                    if media::lookup(declared).is_some_and(|m| m.tier == media::Tier::Header) =>
76                {
77                    declared
78                }
79                _ => media::UNKNOWN_TYPE,
80            },
81        }
82    }
83
84    /// Whether the file is an executable by bytes or by extension.
85    pub fn is_executable(&self) -> bool {
86        self.detected == Detection::Executable
87            || self
88                .extension
89                .as_deref()
90                .is_some_and(media::executable_extension)
91    }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum State {
96    Spooled,
97    Saved,
98    Discarded,
99}
100
101/// The `nitr.File` userdata.
102pub struct LuaFile {
103    info: FileInfo,
104    path: PathBuf,
105    state: Mutex<State>,
106    resolver: SaveResolver,
107    max_text_bytes: u64,
108}
109
110impl LuaFile {
111    /// A handle over a spooled temporary.
112    pub fn new(info: FileInfo, path: PathBuf, resolver: SaveResolver, max_text_bytes: u64) -> Self {
113        Self {
114            info,
115            path,
116            state: Mutex::new(State::Spooled),
117            resolver,
118            max_text_bytes,
119        }
120    }
121
122    /// What detection learned.
123    pub fn info(&self) -> &FileInfo {
124        &self.info
125    }
126
127    fn state(&self) -> State {
128        self.state.lock().map(|s| *s).unwrap_or(State::Discarded)
129    }
130
131    fn set_state(&self, state: State) {
132        if let Ok(mut s) = self.state.lock() {
133            *s = state;
134        }
135    }
136
137    fn require_spooled(&self) -> mlua::Result<()> {
138        match self.state() {
139            State::Spooled => Ok(()),
140            State::Saved => Err(mlua::Error::RuntimeError(
141                "the file was already saved; read it from where it was saved".into(),
142            )),
143            State::Discarded => Err(mlua::Error::RuntimeError(
144                "the file was already discarded".into(),
145            )),
146        }
147    }
148}
149
150impl Drop for LuaFile {
151    fn drop(&mut self) {
152        // Best effort: the server's per-request guard removes the whole
153        // spool directory as well.
154        if self.state() == State::Spooled {
155            let _ = std::fs::remove_file(&self.path);
156        }
157    }
158}
159
160impl UserData for LuaFile {
161    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
162        fields.add_field_method_get("filename", |_, f| Ok(f.info.filename.clone()));
163        fields.add_field_method_get("safe_filename", |_, f| Ok(f.info.safe_filename.clone()));
164        fields.add_field_method_get("extension", |_, f| Ok(f.info.extension.clone()));
165        fields.add_field_method_get("content_type", |_, f| {
166            Ok(f.info.effective_type().to_string())
167        });
168        fields.add_field_method_get("size", |_, f| Ok(f.info.size));
169        fields.add_field_method_get("width", |_, f| Ok(f.info.width));
170        fields.add_field_method_get("height", |_, f| Ok(f.info.height));
171    }
172
173    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
174        // file:save(rel) -> path: renames the temporary into the upload
175        // root (atomic on the same filesystem), through the server's
176        // containment rule.
177        methods.add_async_method("save", |_, file, rel: String| async move {
178            file.require_spooled()?;
179            let target = (file.resolver)(rel.clone()).await?;
180            tokio::fs::rename(&file.path, &target)
181                .await
182                .map_err(|err| {
183                    mlua::Error::RuntimeError(format!("failed to save `{rel}`: {err}"))
184                })?;
185            file.set_state(State::Saved);
186            Ok(target.display().to_string())
187        });
188
189        // file:text() -> string: the contents, only for a small file.
190        methods.add_async_method("text", |lua, file, ()| async move {
191            file.require_spooled()?;
192            if file.info.size > file.max_text_bytes {
193                return Err(mlua::Error::RuntimeError(format!(
194                    "file:text() reads at most {} bytes ([limits] max_field_bytes); this file has {}",
195                    file.max_text_bytes, file.info.size
196                )));
197            }
198            let bytes = tokio::fs::read(&file.path).await.into_lua_err()?;
199            lua.create_string(bytes)
200        });
201
202        // file:hash(algo?) -> hex: streamed from disk; sha256 only today.
203        methods.add_async_method("hash", |_, file, algo: Option<String>| async move {
204            file.require_spooled()?;
205            if let Some(algo) = &algo
206                && algo != "sha256"
207            {
208                return Err(mlua::Error::RuntimeError(format!(
209                    "file:hash(): unknown algorithm `{algo}` (supported: sha256)"
210                )));
211            }
212            use sha2::Digest as _;
213            use tokio::io::AsyncReadExt as _;
214            let mut reader = tokio::fs::File::open(&file.path).await.into_lua_err()?;
215            let mut hasher = sha2::Sha256::new();
216            let mut buf = vec![0u8; 64 * 1024];
217            loop {
218                let n = reader.read(&mut buf).await.into_lua_err()?;
219                if n == 0 {
220                    break;
221                }
222                hasher.update(&buf[..n]);
223            }
224            Ok(hex(&hasher.finalize()))
225        });
226
227        // file:discard(): drop the temporary now.
228        methods.add_async_method("discard", |_, file, ()| async move {
229            file.require_spooled()?;
230            let _ = tokio::fs::remove_file(&file.path).await;
231            file.set_state(State::Discarded);
232            Ok(())
233        });
234    }
235}
236
237fn hex(bytes: &[u8]) -> String {
238    use std::fmt::Write as _;
239    let mut out = String::with_capacity(bytes.len() * 2);
240    for b in bytes {
241        let _ = write!(out, "{b:02x}");
242    }
243    out
244}