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 (attachment defaults)
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`]).
252pub fn referenced(state: &State) -> BTreeSet<String> {
253    let mut out = BTreeSet::new();
254    for part in state.parts.iter() {
255        out.extend(part.attachments.iter().map(|a| a.sha256.clone()));
256        for revision in &part.revisions {
257            out.extend(revision.attachments.iter().map(|a| a.sha256.clone()));
258            out.extend(revision.thumbnail.iter().map(|t| t.sha256.clone()));
259        }
260    }
261    for entry in state.workspace.iter() {
262        out.extend(entry.versions.iter().map(|v| v.sha256.clone()));
263    }
264    out
265}
266
267/// Remove the blob `sha256` if nothing in `state` references it any more.
268/// Called inside the write lock by the change that dropped a reference.
269pub fn remove_if_unreferenced(state: &State, root: &Path, sha256: &str) -> Result<(), Error> {
270    if !is_sha256(sha256) || referenced(state).contains(sha256) {
271        return Ok(());
272    }
273    match std::fs::remove_file(blob_path(root, sha256)) {
274        Err(error) if error.kind() != io::ErrorKind::NotFound => Err(Error::internal(error)),
275        _ => Ok(()),
276    }
277}
278
279/// Move a staged upload to its content address, unless that blob is already
280/// there. Inside the write lock, in the change that adds its reference.
281pub fn place(root: &Path, staged: &Staged) -> Result<(), Error> {
282    let target = blob_path(root, &staged.sha256);
283    if !target.exists() {
284        std::fs::create_dir_all(target.parent().expect("a blob has a directory")).map_err(Error::internal)?;
285        std::fs::rename(&staged.path, &target).map_err(Error::internal)?;
286    }
287    Ok(())
288}
289
290/// The refusal for changing a revision's files, if any: it must be in work
291/// and not checked out by someone else.
292fn revision_writable(state: &State, user: &User, part: &Part, revision_id: &str) -> Result<(), Error> {
293    let revision = part.revision(revision_id).ok_or_else(|| Error::not_found("revision"))?;
294    if !revision.lifecycle.is_editable() {
295        return Err(Error::conflict(format!(
296            "{} revision {} is {} — its files are frozen with it; attach to a new revision",
297            part.number,
298            revision.label,
299            revision.lifecycle.as_str()
300        )));
301    }
302    if let Some(lock) = revision.lock.as_ref().filter(|l| l.user_id != user.id) {
303        let holder = state.user(&lock.user_id).map(|u| u.username.clone()).unwrap_or_else(|| "another user".into());
304        return Err(Error::conflict(format!(
305            "{} revision {} is checked out by {holder}",
306            part.number, revision.label
307        )));
308    }
309    Ok(())
310}
311
312impl Db {
313    /// The data directory's blob path for `sha256`.
314    pub fn blob_path(&self, sha256: &str) -> PathBuf {
315        blob_path(self.root(), sha256)
316    }
317
318    /// Begin streaming an upload, with the server's size limit.
319    pub fn start_upload(&self) -> Result<Upload, Error> {
320        Upload::start(self.root(), self.security().config.attachment_limit()).map_err(Error::internal)
321    }
322
323    /// Attach a staged upload to a part (`revision` empty) or to one of its
324    /// revisions.
325    pub fn attach(
326        &self,
327        user: &User,
328        part_key: &str,
329        revision_key: &str,
330        staged: Staged,
331        describe: &Describe,
332    ) -> Result<Attachment, Error> {
333        let (sha256, size) = (staged.sha256.clone(), staged.size);
334        self.attach_blob(user, part_key, revision_key, &sha256, size, Some(staged), describe, |_| Ok(()))
335    }
336
337    /// [`Db::attach`] for bytes that are either a staged upload or, with
338    /// `staged` absent, a blob the store already holds (a workspace file
339    /// promoted to an attachment). `check` runs inside the lock first, so a
340    /// caller can prove its blob is still referenced at the write.
341    #[allow(clippy::too_many_arguments)]
342    pub fn attach_blob(
343        &self,
344        user: &User,
345        part_key: &str,
346        revision_key: &str,
347        sha256: &str,
348        size: u64,
349        staged: Option<Staged>,
350        describe: &Describe,
351        check: impl FnOnce(&State) -> Result<(), Error>,
352    ) -> Result<Attachment, Error> {
353        if !user.can_author() {
354            return Err(Error::forbidden("attaching a file needs the author group"));
355        }
356        let name = clean_name(&describe.name)?;
357        let media_type = clean_media_type(&describe.media_type);
358        let kind = clean_kind(&describe.kind, &media_type)?;
359        let note = describe.note.trim().to_string();
360        if note.chars().count() > MAX_NOTE {
361            return Err(Error::bad_request(format!("a note is at most {MAX_NOTE} characters")));
362        }
363        if !is_sha256(sha256) {
364            return Err(Error::internal("an attachment names no valid blob"));
365        }
366        let root = self.root().to_path_buf();
367        let user_id = user.id.clone();
368        let user = user.clone();
369        self.mutate(move |state| {
370            check(state)?;
371            let part = state.part_by_id_or_number(part_key).ok_or_else(|| Error::not_found("part"))?;
372            let part_id = part.id.clone();
373            let revision_id = if revision_key.trim().is_empty() {
374                None
375            } else {
376                let r = crate::bom::find_revision(part, revision_key).ok_or_else(|| Error::not_found("revision"))?;
377                Some(r.id.clone())
378            };
379            if let Some(revision_id) = &revision_id {
380                revision_writable(state, &user, part, revision_id)?;
381            }
382            let attachment = Attachment {
383                id: crate::auth::new_id(),
384                name,
385                media_type,
386                size,
387                sha256: sha256.to_string(),
388                kind,
389                note,
390                uploaded_by: user_id,
391                uploaded_at: now(),
392            };
393            // The bytes reach their address inside the lock, so no delete of
394            // the same content can remove them between here and the commit.
395            match &staged {
396                Some(staged) => place(&root, staged)?,
397                None if !blob_path(&root, sha256).exists() => {
398                    return Err(Error::internal(format!("the stored file {sha256} is missing")))
399                }
400                None => {}
401            }
402            let part = state.parts.get_mut(&part_id).ok_or_else(|| Error::not_found("part"))?;
403            match &revision_id {
404                None => part.attachments.push(attachment.clone()),
405                Some(id) => {
406                    let revision = part.revision_mut(id).ok_or_else(|| Error::not_found("revision"))?;
407                    revision.attachments.push(attachment.clone());
408                    revision.modified_at = now();
409                }
410            }
411            Ok(attachment)
412        })
413    }
414
415    /// Replace exactly one attachment reference atomically. A fresh id protects
416    /// copies carried into other revisions; their original bytes remain intact.
417    pub fn replace_attachment(&self, user: &User, id: &str, part: &str, revision: &str,
418        expected_hash: &str, staged: Staged) -> Result<Located, Error> {
419        let root = self.root().to_path_buf();
420        self.mutate(|state| {
421            let found = locate_scoped(state, id, part, revision).ok_or_else(|| Error::not_found("attachment"))?;
422            attachment_writable(state, user, &found)?;
423            if found.attachment.sha256 != expected_hash { return Err(Error::conflict("This file changed since you opened it. Reopen it before saving.")); }
424            let mut changed = found.clone();
425            changed.attachment.id = crate::auth::new_id();
426            changed.attachment.sha256 = staged.sha256.clone();changed.attachment.size = staged.size;
427            changed.attachment.uploaded_by = user.id.clone();changed.attachment.uploaded_at = now();
428            place(&root, &staged)?;
429            let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
430            let files = if found.revision_id.is_empty() { &mut part.attachments } else {
431                let r = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
432                r.modified_at = now();&mut r.attachments
433            };
434            let file = files.iter_mut().find(|a| a.id == id).ok_or_else(|| Error::not_found("attachment"))?;
435            *file = changed.attachment.clone();
436            remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
437            Ok(changed)
438        })
439    }
440
441    /// Remove one attachment reference; the blob goes with its last one.
442    pub fn detach(&self, user: &User, id: &str) -> Result<Located, Error> {
443        if !user.can_author() {
444            return Err(Error::forbidden("removing a file needs the author group"));
445        }
446        let root = self.root().to_path_buf();
447        let user = user.clone();
448        self.mutate(move |state| {
449            let found = locate(state, id).ok_or_else(|| Error::not_found("attachment"))?;
450            let part = state.part(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
451            if !found.revision_id.is_empty() {
452                revision_writable(state, &user, part, &found.revision_id)?;
453            }
454            let part = state.parts.get_mut(&found.part_id).ok_or_else(|| Error::not_found("part"))?;
455            if found.revision_id.is_empty() {
456                part.attachments.retain(|a| a.id != id);
457            } else {
458                let revision = part.revision_mut(&found.revision_id).ok_or_else(|| Error::not_found("revision"))?;
459                revision.attachments.retain(|a| a.id != id);
460                revision.modified_at = now();
461            }
462            remove_if_unreferenced(state, &root, &found.attachment.sha256)?;
463            Ok(found)
464        })
465    }
466
467    /// Find an attachment by id.
468    pub fn attachment(&self, id: &str) -> Option<Located> {
469        self.read(|state| locate(state, id))
470    }
471
472    /// Remove blobs nothing references and uploads left in staging — what a
473    /// crash between moving a blob and committing its reference can leave.
474    /// For start-up, before the server takes requests (one process owns the
475    /// directory, see [`crate::dirlock`]); returns how many files went.
476    pub fn sweep_blobs(&self) -> io::Result<usize> {
477        let root = blob_root(self.root());
478        if !root.exists() {
479            return Ok(0);
480        }
481        let keep = self.read(referenced);
482        let staging = staging_dir(self.root());
483        let mut removed = 0;
484        if staging.exists() {
485            for entry in std::fs::read_dir(&staging)? {
486                std::fs::remove_file(entry?.path())?;
487                removed += 1;
488            }
489        }
490        for shard in std::fs::read_dir(&root)? {
491            let shard = shard?.path();
492            if !shard.is_dir() || shard == staging {
493                continue;
494            }
495            for entry in std::fs::read_dir(&shard)? {
496                let path = entry?.path();
497                let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
498                if is_sha256(&name) && !keep.contains(&name) {
499                    std::fs::remove_file(&path)?;
500                    removed += 1;
501                }
502            }
503        }
504        Ok(removed)
505    }
506}