Skip to main content

brep_plm/
attach.rs

1//! Attachments: files on a part or on one of its revisions.
2//!
3//! # Where the bytes are
4//!
5//! `<data>/blobs/<first two hex>/<sha256>` — content-addressed, so the same
6//! file attached twice (to two parts, or carried to a new revision) is stored
7//! once. An upload streams into `<data>/blobs/tmp/` while it is hashed and
8//! counted against the size limit, and is never held in memory whole; it is
9//! moved to its content address inside the store's write lock, in the same
10//! change that adds its reference. A blob is removed inside the write lock
11//! too, by the change that drops its last reference, so an upload and a
12//! delete of the same content can never cross.
13//!
14//! # The rules
15//!
16//! - A PART attachment follows the part, like sourcing: any author may add or
17//!   remove one at any time, released revisions or not.
18//! - A REVISION attachment is frozen with the revision: it is added or removed
19//!   only while the revision is in work and nobody else holds its lock. A new
20//!   revision starts with references to the same files.
21//! - Download is for anyone signed in. A small list of media types that a
22//!   browser renders without running anything (raster images and PDF) may be
23//!   shown inline; everything else is served as a download. The page's
24//!   Content-Security-Policy and `nosniff` stay on every response.
25
26use std::collections::BTreeSet;
27use std::io;
28use std::path::{Path, PathBuf};
29
30use serde::Serialize;
31use sha2::{Digest, Sha256};
32
33use crate::db::{now, Db, State};
34use crate::model::{Attachment, Part, User};
35use crate::Error;
36
37/// The kinds an attachment may be filed as.
38pub const KINDS: [&str; 5] = ["datasheet", "drawing", "spec", "image", "other"];
39
40/// Media types a browser may show inline: they render without script.
41/// SVG is an image that can carry script, so it is NOT here.
42pub const INLINE_TYPES: [&str; 5] = ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
43
44const MAX_NAME: usize = 200;
45const MAX_NOTE: usize = 500;
46
47/// The blob directory under a data directory.
48pub fn blob_root(data: &Path) -> PathBuf {
49    data.join("blobs")
50}
51
52/// Where the blob with this hash lives.
53pub fn blob_path(data: &Path, sha256: &str) -> PathBuf {
54    blob_root(data).join(&sha256[..2]).join(sha256)
55}
56
57/// Where uploads stream to before they have a name.
58pub fn staging_dir(data: &Path) -> PathBuf {
59    blob_root(data).join("tmp")
60}
61
62/// Whether `text` is a hex SHA-256 — the only thing ever joined to a blob path.
63pub fn is_sha256(text: &str) -> bool {
64    text.len() == 64 && text.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
65}
66
67/// An upload that has been written, hashed and counted, and waits in the
68/// staging directory for its reference. Dropping it removes the file, so an
69/// upload that is refused or abandoned leaves nothing behind.
70#[derive(Debug)]
71pub struct Staged {
72    pub path: PathBuf,
73    pub sha256: String,
74    pub size: u64,
75}
76
77impl Drop for Staged {
78    fn drop(&mut self) {
79        let _ = std::fs::remove_file(&self.path);
80    }
81}
82
83/// Hashes and counts an upload as it streams to the staging directory.
84pub struct Upload {
85    file: std::fs::File,
86    path: PathBuf,
87    hasher: Sha256,
88    size: u64,
89    limit: u64,
90    done: bool,
91}
92
93impl Upload {
94    pub fn start(data: &Path, limit: u64) -> io::Result<Upload> {
95        let dir = staging_dir(data);
96        std::fs::create_dir_all(&dir)?;
97        let path = dir.join(format!("{}.part", crate::auth::new_id()));
98        let file = std::fs::File::create(&path)?;
99        Ok(Upload { file, path, hasher: Sha256::new(), size: 0, limit, done: false })
100    }
101
102    /// Append a chunk. Over the limit is a `413`, and the partial file goes.
103    pub fn write(&mut self, chunk: &[u8]) -> Result<(), Error> {
104        use std::io::Write;
105        self.size += chunk.len() as u64;
106        if self.size > self.limit {
107            return Err(Error {
108                status: axum::http::StatusCode::PAYLOAD_TOO_LARGE,
109                message: format!("the file is over the {} MB attachment limit", self.limit / (1024 * 1024)),
110            });
111        }
112        self.hasher.update(chunk);
113        self.file.write_all(chunk).map_err(Error::internal)
114    }
115
116    /// The file is complete: flush it and hand it on.
117    pub fn finish(self) -> Result<Staged, Error> { self.finish_with_empty(false) }
118
119    pub(crate) fn finish_with_empty(mut self, allow_empty: bool) -> Result<Staged, Error> {
120        if self.size == 0 && !allow_empty {
121            return Err(Error::bad_request("the file is empty"));
122        }
123        self.file.sync_all().map_err(Error::internal)?;
124        self.done = true;
125        let sha256 = format!("{:x}", std::mem::take(&mut self.hasher).finalize());
126        Ok(Staged { path: std::mem::take(&mut self.path), sha256, size: self.size })
127    }
128}
129
130impl Drop for Upload {
131    fn drop(&mut self) {
132        if !self.done {
133            let _ = std::fs::remove_file(&self.path);
134        }
135    }
136}
137
138/// What the uploader says about a file.
139#[derive(Debug, Clone, Default)]
140pub struct Describe {
141    pub name: String,
142    pub media_type: String,
143    pub kind: String,
144    pub note: String,
145}
146
147/// A file name that is safe to store and to put in a `Content-Disposition`:
148/// the last path segment, no control characters or quotes, not empty.
149pub fn clean_name(raw: &str) -> Result<String, Error> {
150    let last = raw.rsplit(['/', '\\']).next().unwrap_or("").trim();
151    let name: String = last.chars().filter(|c| !c.is_control() && *c != '"').collect();
152    let name = name.trim().to_string();
153    if name.is_empty() || name == "." || name == ".." {
154        return Err(Error::bad_request("an attachment needs a file name"));
155    }
156    if name.chars().count() > MAX_NAME {
157        return Err(Error::bad_request(format!("a file name is at most {MAX_NAME} characters")));
158    }
159    Ok(name)
160}
161
162/// A media type in `type/subtype` form, lower case, parameters dropped; else
163/// `application/octet-stream`.
164pub fn clean_media_type(raw: &str) -> String {
165    let base = raw.split(';').next().unwrap_or("").trim().to_ascii_lowercase();
166    let ok = |part: &str| {
167        !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
168    };
169    match base.split_once('/') {
170        Some((a, b)) if ok(a) && ok(b) => base,
171        _ => "application/octet-stream".to_string(),
172    }
173}
174
175fn clean_kind(raw: &str, media_type: &str) -> Result<String, Error> {
176    let kind = raw.trim().to_ascii_lowercase();
177    if kind.is_empty() {
178        return Ok(if media_type.starts_with("image/") { "image" } else { "other" }.to_string());
179    }
180    if KINDS.contains(&kind.as_str()) {
181        Ok(kind)
182    } else {
183        Err(Error::bad_request(format!("'{kind}' is not a kind of attachment — {}", KINDS.join(", "))))
184    }
185}
186
187/// Whether a response may show this type inline.
188pub fn inline_ok(media_type: &str) -> bool {
189    INLINE_TYPES.contains(&media_type)
190}
191
192/// Where an attachment hangs, found by its id.
193#[derive(Debug, Clone, Serialize)]
194pub struct Located {
195    pub attachment: Attachment,
196    pub part_id: String,
197    pub number: String,
198    /// Empty for a part attachment.
199    pub revision_id: String,
200    pub revision_label: String,
201}
202
203/// Find an attachment by id anywhere in the store.
204pub fn locate(state: &State, id: &str) -> Option<Located> {
205    for part in state.parts.iter() {
206        if let Some(a) = part.attachments.iter().find(|a| a.id == id) {
207            return Some(Located {
208                attachment: a.clone(),
209                part_id: part.id.clone(),
210                number: part.number.clone(),
211                revision_id: String::new(),
212                revision_label: String::new(),
213            });
214        }
215        for revision in &part.revisions {
216            if let Some(a) = revision.attachments.iter().find(|a| a.id == id) {
217                return Some(Located {
218                    attachment: a.clone(),
219                    part_id: part.id.clone(),
220                    number: part.number.clone(),
221                    revision_id: revision.id.clone(),
222                    revision_label: revision.label.clone(),
223                });
224            }
225        }
226    }
227    None
228}
229
230/// Resolve a file in a particular part/revision; carried attachments can share ids.
231pub fn locate_scoped(state: &State, id: &str, part_key: &str, revision_key: &str) -> Option<Located> {
232    if part_key.is_empty() { return locate(state, id); }
233    let part = state.part_by_id_or_number(part_key)?;
234    let revision = if revision_key.is_empty() { None } else { Some(crate::bom::find_revision(part, revision_key)?) };
235    let files = revision.map(|r| &r.attachments).unwrap_or(&part.attachments);
236    let attachment = files.iter().find(|a| a.id == id)?.clone();
237    Some(Located { attachment, part_id: part.id.clone(), number: part.number.clone(),
238        revision_id: revision.map(|r| r.id.clone()).unwrap_or_default(),
239        revision_label: revision.map(|r| r.label.clone()).unwrap_or_default() })
240}
241
242pub fn attachment_writable(state: &State, user: &User, found: &Located) -> Result<(), Error> {
243    if !user.can_author() { return Err(Error::forbidden("editing an attachment needs the author group")); }
244    let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
245    if !found.revision_id.is_empty() { revision_writable(state, user, part, &found.revision_id)?; }
246    Ok(())
247}
248
249/// Every blob the store references: attachments, revision thumbnails
250/// ([`crate::thumbnail`]), and every version of every workspace file
251/// ([`crate::workspace`]), instructions player data ([`crate::player`]), and
252/// the tools library's pictures ([`crate::tools`]).
253pub fn referenced(state: &State) -> BTreeSet<String> {
254    let mut out = BTreeSet::new();
255    for part in state.parts.iter() {
256        out.extend(part.attachments.iter().map(|a| a.sha256.clone()));
257        for revision in &part.revisions {
258            out.extend(revision.attachments.iter().map(|a| a.sha256.clone()));
259            out.extend(revision.thumbnail.iter().map(|t| t.sha256.clone()));
260            out.extend(revision.player.iter().map(|p| p.sha256.clone()));
261        }
262    }
263    for entry in state.workspace.iter() {
264        out.extend(entry.versions.iter().map(|v| v.sha256.clone()));
265    }
266    out.extend(crate::tools::pictures(state).map(str::to_string));
267    out
268}
269
270/// The stores whose own backup is copying their blobs now, each with the
271/// blobs whose last reference went meanwhile: their files stay until the
272/// backup ends ([`BlobsHeld`]), so a backup never loses a blob its snapshot
273/// references. Keyed by the store's root: several stores share a process in
274/// the tests.
275static HELD: std::sync::Mutex<Vec<(std::path::PathBuf, Vec<String>)>> = std::sync::Mutex::new(Vec::new());
276
277/// Blob removals of the store at a root held while it lives; the held ones
278/// are made by [`BlobsHeld::release`].
279pub struct BlobsHeld(std::path::PathBuf);
280
281impl BlobsHeld {
282    pub fn new(root: &Path) -> Self {
283        HELD.lock().unwrap_or_else(|e| e.into_inner()).push((root.to_path_buf(), Vec::new()));
284        Self(root.to_path_buf())
285    }
286
287    /// Stop holding, and remove the held blobs that are still unreferenced.
288    /// Under the store's read lock: no change can reference one meanwhile.
289    pub fn release(self, db: &crate::db::Db) -> Result<(), Error> {
290        let held = take_held(&self.0);
291        db.read(|state| held.iter().try_for_each(|sha| remove_if_unreferenced(state, &self.0, sha)))
292    }
293}
294
295impl Drop for BlobsHeld {
296    fn drop(&mut self) {
297        // Released or not, the hold ends with the backup. Files not released
298        // are orphans the start-up sweep removes.
299        take_held(&self.0);
300    }
301}
302
303fn take_held(root: &Path) -> Vec<String> {
304    let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner());
305    match held.iter().position(|(r, _)| r == root) {
306        Some(i) => held.remove(i).1,
307        None => Vec::new(),
308    }
309}
310
311/// Remove the blob `sha256` if nothing in `state` references it any more.
312/// Called inside the write lock by the change that dropped a reference.
313/// While the store's own backup copies blobs, the removal waits for it.
314pub fn remove_if_unreferenced(state: &State, root: &Path, sha256: &str) -> Result<(), Error> {
315    if !is_sha256(sha256) || referenced(state).contains(sha256) {
316        return Ok(());
317    }
318    {
319        let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner());
320        if let Some((_, waiting)) = held.iter_mut().find(|(r, _)| r == root) {
321            waiting.push(sha256.to_string());
322            return Ok(());
323        }
324    }
325    match std::fs::remove_file(blob_path(root, sha256)) {
326        Err(error) if error.kind() != io::ErrorKind::NotFound => Err(Error::internal(error)),
327        _ => Ok(()),
328    }
329}
330
331/// Move a staged upload to its content address, unless that blob is already
332/// there. Inside the write lock, in the change that adds its reference.
333pub fn place(root: &Path, staged: &Staged) -> Result<(), Error> {
334    let target = blob_path(root, &staged.sha256);
335    if !target.exists() {
336        std::fs::create_dir_all(target.parent().expect("a blob has a directory")).map_err(Error::internal)?;
337        std::fs::rename(&staged.path, &target).map_err(Error::internal)?;
338    }
339    Ok(())
340}
341
342/// The refusal for changing a revision's files, if any: it must be in work
343/// and not checked out by someone else.
344fn revision_writable(state: &State, user: &User, part: &Part, revision_id: &str) -> Result<(), Error> {
345    let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
346    if !revision.lifecycle.is_editable() {
347        return Err(Error::conflict(format!(
348            "{} revision {} is {} — its files are frozen with it; attach to a new revision",
349            part.number,
350            revision.label,
351            revision.lifecycle.as_str()
352        )));
353    }
354    if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
355        let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
356        return Err(Error::conflict(format!(
357            "{} revision {} is checked out by {holder}",
358            part.number, revision.label
359        )));
360    }
361    Ok(())
362}
363
364impl Db {
365    /// The data directory's blob path for `sha256`.
366    pub fn blob_path(&self, sha256: &str) -> PathBuf {
367        blob_path(self.root(), sha256)
368    }
369
370    /// Begin streaming an upload, with the server's size limit.
371    pub fn start_upload(&self) -> Result<Upload, Error> {
372        Upload::start(self.root(), self.security().config.attachment_limit()).map_err(Error::internal)
373    }
374
375    /// Attach a staged upload to a part (`revision` empty) or to one of its
376    /// revisions.
377    pub fn attach(
378        &self,
379        user: &User,
380        part_key: &str,
381        revision_key: &str,
382        staged: Staged,
383        describe: &Describe,
384    ) -> Result<Attachment, Error> {
385        let (sha256, size) = (staged.sha256.clone(), staged.size);
386        self.attach_blob(user, part_key, revision_key, &sha256, size, Some(staged), describe, |_| Ok(()))
387    }
388
389    /// [`Db::attach`] for bytes that are either a staged upload or, with
390    /// `staged` absent, a blob the store already holds (a workspace file
391    /// promoted to an attachment). `check` runs inside the lock first, so a
392    /// caller can prove its blob is still referenced at the write.
393    #[allow(clippy::too_many_arguments)]
394    pub fn attach_blob(
395        &self,
396        user: &User,
397        part_key: &str,
398        revision_key: &str,
399        sha256: &str,
400        size: u64,
401        staged: Option<Staged>,
402        describe: &Describe,
403        check: impl FnOnce(&State) -> Result<(), Error>,
404    ) -> Result<Attachment, Error> {
405        if !user.can_author() {
406            return Err(Error::forbidden("attaching a file needs the author group"));
407        }
408        let name = clean_name(&describe.name)?;
409        let media_type = clean_media_type(&describe.media_type);
410        let kind = clean_kind(&describe.kind, &media_type)?;
411        let note = describe.note.trim().to_string();
412        if note.chars().count() > MAX_NOTE {
413            return Err(Error::bad_request(format!("a note is at most {MAX_NOTE} characters")));
414        }
415        if !is_sha256(sha256) {
416            return Err(Error::internal("an attachment names no valid blob"));
417        }
418        let root = self.root().to_path_buf();
419        let user_id = user.id.clone();
420        let user = user.clone();
421        self.mutate(move |state| {
422            check(state)?;
423            let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
424            let part_id = part.id.clone();
425            let revision_id = if revision_key.trim().is_empty() {
426                None
427            } else {
428                let r = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
429                Some(r.id.clone())
430            };
431            if let Some(revision_id) = &revision_id {
432                revision_writable(state, &user, part, revision_id)?;
433            }
434            let attachment = Attachment {
435                id: crate::auth::new_id(),
436                name,
437                media_type,
438                size,
439                sha256: sha256.to_string(),
440                kind,
441                note,
442                uploaded_by: user_id,
443                uploaded_at: now(),
444            };
445            // The bytes reach their address inside the lock, so no delete of
446            // the same content can remove them between here and the commit.
447            match &staged {
448                Some(staged) => place(&root, staged)?,
449                None if !blob_path(&root, sha256).exists() => {
450                    return Err(Error::internal(format!("the stored file {sha256} is missing")))
451                }
452                None => {}
453            }
454            let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
455            match &revision_id {
456                None => part.attachments.push(attachment.clone()),
457                Some(id) => {
458                    let revision = part.revision_mut(id).ok_or_else(|| Error::not_found("revision"))?;
459                    revision.attachments.push(attachment.clone());
460                    revision.modified_at = now();
461                }
462            }
463            Ok(attachment)
464        })
465    }
466
467    /// Replace exactly one attachment reference atomically. A fresh id protects
468    /// copies carried into other revisions; their original bytes remain intact.
469    pub fn replace_attachment(&self, user: &User, id: &str, part: &str, revision: &str,
470        expected_hash: &str, staged: Staged) -> Result<Located, Error> {
471        let root = self.root().to_path_buf();
472        self.mutate(|state| {
473            let found = locate_scoped(state, id, part, revision).ok_or_else(|| Error::not_found("attachment"))?;
474            attachment_writable(state, user, &found)?;
475            if found.attachment.sha256 != expected_hash { return Err(Error::conflict("This file changed since you opened it. Reopen it before saving.")); }
476            let mut changed = found.clone();
477            changed.attachment.id = crate::auth::new_id();
478            changed.attachment.sha256 = staged.sha256.clone();changed.attachment.size = staged.size;
479            changed.attachment.uploaded_by = user.id.clone();changed.attachment.uploaded_at = now();
480            place(&root, &staged)?;
481            let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
482            let files = if found.revision_id.is_empty() { &mut part.attachments } else {
483                let r = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
484                r.modified_at = now();&mut r.attachments
485            };
486            let file = files.iter_mut().find(|a| a.id == id).ok_or_else(|| Error::not_found("attachment"))?;
487            *file = changed.attachment.clone();
488            remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
489            Ok(changed)
490        })
491    }
492
493    /// Remove one attachment reference; the blob goes with its last one.
494    pub fn detach(&self, user: &User, id: &str) -> Result<Located, Error> {
495        if !user.can_author() {
496            return Err(Error::forbidden("removing a file needs the author group"));
497        }
498        let root = self.root().to_path_buf();
499        let user = user.clone();
500        self.mutate(move |state| {
501            let found = locate(state, id).ok_or_else(|| Error::not_found("attachment"))?;
502            let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
503            if !found.revision_id.is_empty() {
504                revision_writable(state, &user, part, &found.revision_id)?;
505            }
506            let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
507            if found.revision_id.is_empty() {
508                part.attachments.retain(|a| a.id != id);
509            } else {
510                let revision = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
511                revision.attachments.retain(|a| a.id != id);
512                revision.modified_at = now();
513            }
514            remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
515            Ok(found)
516        })
517    }
518
519    /// Find an attachment by id.
520    pub fn attachment(&self, id: &str) -> Option<Located> {
521        self.read(|state| locate(state, id))
522    }
523
524    /// Remove blobs nothing references and uploads left in staging — what a
525    /// crash between moving a blob and committing its reference can leave.
526    /// For start-up, before the server takes requests (one process owns the
527    /// directory, see [`crate::dirlock`]); returns how many files went.
528    pub fn sweep_blobs(&self) -> io::Result<usize> {
529        let root = blob_root(self.root());
530        if !root.exists() {
531            return Ok(0);
532        }
533        let keep = self.read(referenced);
534        let staging = staging_dir(self.root());
535        let mut removed = 0;
536        if staging.exists() {
537            for entry in std::fs::read_dir(&staging)? {
538                std::fs::remove_file(entry?.path())?;
539                removed += 1;
540            }
541        }
542        for shard in std::fs::read_dir(&root)? {
543            let shard = shard?.path();
544            if !shard.is_dir() || shard == staging {
545                continue;
546            }
547            for entry in std::fs::read_dir(&shard)? {
548                let path = entry?.path();
549                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
550                if is_sha256(&name) && !keep.contains(&name) {
551                    std::fs::remove_file(&path)?;
552                    removed += 1;
553                }
554            }
555        }
556        Ok(removed)
557    }
558}