forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

note_file.rs202 lines, 6.6 KiBHistoryRawDownload
1//! A file attached to a note. The row carries metadata only (original
2//! filename, MIME type, byte size); the bytes themselves live on disk under
3//! [`crate::config::Config::files_path`], in a file named by this row's key —
4//! a server-generated UUIDv7, so no user input ever shapes a disk path. The
5//! web layer owns the blob I/O and its ordering (blob before row on upload,
6//! row before blob on delete); persistence lives in [`crate::db::note_file`].
7
8use uuid::Uuid;
9
10use crate::constant::{MAX_FILE_CONTENT_TYPE_LEN, MAX_FILE_NAME_LEN};
11use crate::domain::monotonic_id::next_uuid;
12use crate::domain::note::NoteId;
13use crate::error::ValidationError;
14
15/// Typed note-file row id. A UUIDv7 minted by the process-wide monotonic
16/// generator, so `id` order is mint order.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, sqlx::Type)]
18#[sqlx(transparent)]
19pub struct NoteFileId(Uuid);
20
21impl NoteFileId {
22 /// Minted from the process-wide monotonic generator, not a random v4:
23 /// a note's files list `id DESC` (newest first,
24 /// [`crate::db::note_file::list_for`]), and a random low half scrambles
25 /// rows minted in the same millisecond.
26 pub fn generate() -> Self {
27 Self(next_uuid())
28 }
29
30 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
31 /// cannot take the newtype. Static `query!` binds take `self` directly.
32 pub fn uuid(&self) -> Uuid {
33 self.0
34 }
35
36 /// Parse a wire key. A key that parses as no UUID — a malformed path
37 /// segment — reads as the nil id, which matches no row: exactly the 404 a
38 /// dangling record key produced under the old store, without turning a
39 /// typo into a panic.
40 pub fn from_key(key: &str) -> Self {
41 Self(Uuid::parse_str(key).unwrap_or(Uuid::nil()))
42 }
43
44 /// The hyphenated wire form.
45 pub fn key(&self) -> String {
46 self.0.to_string()
47 }
48}
49
50/// The uploader's original filename, kept for display and download headers.
51/// Never used as a disk path — but path separators and control characters are
52/// refused anyway: they are not filenames, only header/log injection attempts.
53#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
54#[sqlx(transparent)]
55pub struct FileName(String);
56
57impl FileName {
58 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
59 let value = value.trim();
60 if value.is_empty() {
61 return Err(ValidationError::Empty("filename"));
62 }
63 if value.chars().count() > MAX_FILE_NAME_LEN {
64 return Err(ValidationError::TooLong {
65 field: "filename",
66 max: MAX_FILE_NAME_LEN,
67 got: value.chars().count(),
68 });
69 }
70 if value
71 .chars()
72 .any(|c| c.is_control() || c == '/' || c == '\\')
73 {
74 return Err(ValidationError::Invalid {
75 field: "filename",
76 reason: "must not contain path separators or control characters",
77 });
78 }
79 Ok(Self(value.to_string()))
80 }
81
82 pub fn as_str(&self) -> &str {
83 &self.0
84 }
85}
86
87/// The MIME type the client declared for the file. Blank defaults to
88/// `application/octet-stream`; it is echoed back on download, so it is held
89/// to header-safe ASCII.
90#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
91#[sqlx(transparent)]
92pub struct FileContentType(String);
93
94impl FileContentType {
95 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
96 let value = value.trim();
97 if value.is_empty() {
98 return Ok(Self("application/octet-stream".to_string()));
99 }
100 if value.chars().count() > MAX_FILE_CONTENT_TYPE_LEN {
101 return Err(ValidationError::TooLong {
102 field: "content_type",
103 max: MAX_FILE_CONTENT_TYPE_LEN,
104 got: value.chars().count(),
105 });
106 }
107 if !value.is_ascii() {
108 return Err(ValidationError::NotAscii("content_type"));
109 }
110 if value.chars().any(|c| c.is_ascii_control()) {
111 return Err(ValidationError::Invalid {
112 field: "content_type",
113 reason: "must not contain control characters",
114 });
115 }
116 Ok(Self(value.to_string()))
117 }
118
119 pub fn as_str(&self) -> &str {
120 &self.0
121 }
122}
123
124#[derive(Debug, Clone, sqlx::FromRow)]
125pub struct NoteFile {
126 pub(crate) id: NoteFileId,
127 pub(crate) note: NoteId,
128 pub(crate) name: FileName,
129 pub(crate) content_type: FileContentType,
130 pub(crate) size: i64,
131}
132
133impl NoteFile {
134 /// Assemble a new attachment row (id generated here) without persisting
135 /// it. The caller writes the blob to disk under the fresh id first, then
136 /// calls [`crate::db::note_file::insert`] — so a stored row always points
137 /// at a real blob.
138 pub fn new(note: &NoteId, name: FileName, content_type: FileContentType, size: i64) -> Self {
139 Self {
140 id: NoteFileId::generate(),
141 note: *note,
142 name,
143 content_type,
144 size,
145 }
146 }
147
148 pub fn get_id(&self) -> &NoteFileId {
149 &self.id
150 }
151
152 pub fn get_name(&self) -> &FileName {
153 &self.name
154 }
155
156 pub fn get_content_type(&self) -> &FileContentType {
157 &self.content_type
158 }
159
160 pub fn get_size(&self) -> i64 {
161 self.size
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[tokio::test]
170 async fn filename_rules() {
171 assert_eq!(
172 FileName::try_new(" ödev.pdf ").unwrap().as_str(),
173 "ödev.pdf"
174 );
175 assert!(FileName::try_new("").is_err());
176 assert!(FileName::try_new(" ").is_err());
177 assert!(FileName::try_new(&"x".repeat(256)).is_err());
178 // Path separators and control characters are injection, not filenames.
179 assert!(FileName::try_new("a/b.pdf").is_err());
180 assert!(FileName::try_new("a\\b.pdf").is_err());
181 assert!(FileName::try_new("a\nb.pdf").is_err());
182 assert!(FileName::try_new("a\x00b").is_err());
183 }
184
185 #[tokio::test]
186 async fn content_type_rules() {
187 assert_eq!(
188 FileContentType::try_new("application/pdf")
189 .unwrap()
190 .as_str(),
191 "application/pdf"
192 );
193 // Blank means the client didn't say — fall back, don't fail.
194 assert_eq!(
195 FileContentType::try_new("").unwrap().as_str(),
196 "application/octet-stream"
197 );
198 assert!(FileContentType::try_new(&"x".repeat(101)).is_err());
199 assert!(FileContentType::try_new("appli¢ation/pdf").is_err());
200 assert!(FileContentType::try_new("a\r\nb").is_err());
201 }
202}