Skip to main content

brep_plm/api/
attachments.rs

1//! Attachments over HTTP. The rules are in [`crate::attach`].
2//!
3//! An upload is the file's bytes as the request body — not a multipart form —
4//! with its media type as `Content-Type` and its name, kind and note in the
5//! query string. It streams to disk as it arrives and is refused with `413`
6//! the moment it passes the limit. A download streams from disk.
7
8use axum::body::Body;
9use axum::extract::{Path, Query, State};
10use axum::http::{header, HeaderMap, HeaderValue};
11use axum::response::{IntoResponse, Response};
12use axum::Json;
13use serde::Deserialize;
14use serde_json::{json, Value};
15
16use super::{blocking, require_author, require_user, Shared};
17use crate::attach::{self, Describe};
18use crate::Error;
19
20#[derive(Debug, Deserialize, Default)]
21pub struct UploadQuery {
22    #[serde(default)]
23    pub name: String,
24    #[serde(default)]
25    pub kind: String,
26    #[serde(default)]
27    pub note: String,
28}
29
30/// Stream a request body into the staging directory under the attachment
31/// limit. Workspace files arrive the same way.
32pub(crate) async fn receive(db: &Shared, headers: &HeaderMap, body: Body) -> Result<attach::Staged, Error> {
33    receive_with_empty(db, headers, body, false).await
34}
35
36pub(crate) async fn receive_with_empty(db: &Shared, headers: &HeaderMap, body: Body, allow_empty: bool) -> Result<attach::Staged, Error> {
37    let mut upload = db.start_upload()?;
38    let limit = db.security().config.attachment_limit();
39    if let Some(length) = headers.get(header::CONTENT_LENGTH).and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok()) {
40        if length > limit {
41            return Err(Error {
42                status: axum::http::StatusCode::PAYLOAD_TOO_LARGE,
43                message: format!("the file is over the {} MB attachment limit", limit / (1024 * 1024)),
44            });
45        }
46    }
47    let mut body = body;
48    while let Some(chunk) = super::body_io::next_chunk(&mut body).await {
49        let chunk = chunk.map_err(|e| Error::bad_request(format!("the upload broke off: {e}")))?;
50        upload.write(&chunk)?;
51    }
52    upload.finish_with_empty(allow_empty)
53}
54
55fn describe(headers: &HeaderMap, query: UploadQuery) -> Describe {
56    Describe {
57        name: query.name,
58        media_type: headers
59            .get(header::CONTENT_TYPE)
60            .and_then(|v| v.to_str().ok())
61            .unwrap_or("")
62            .to_string(),
63        kind: query.kind,
64        note: query.note,
65    }
66}
67
68/// Attach a file to a part.
69pub async fn upload_to_part(
70    State(db): State<Shared>,
71    headers: HeaderMap,
72    Path(id): Path<String>,
73    Query(query): Query<UploadQuery>,
74    body: Body,
75) -> Result<Json<Value>, Error> {
76    let user = require_author(&db, &headers)?;
77    let staged = receive(&db, &headers, body).await?;
78    let what = describe(&headers, query);
79    let done = blocking(move || db.attach(&user, &id, "", staged, &what)).await?;
80    Ok(Json(json!({ "ok": true, "attachment": done })))
81}
82
83/// Attach a file to one revision.
84pub async fn upload_to_revision(
85    State(db): State<Shared>,
86    headers: HeaderMap,
87    Path((id, rev)): Path<(String, String)>,
88    Query(query): Query<UploadQuery>,
89    body: Body,
90) -> Result<Json<Value>, Error> {
91    let user = require_author(&db, &headers)?;
92    let staged = receive(&db, &headers, body).await?;
93    let what = describe(&headers, query);
94    let done = blocking(move || db.attach(&user, &id, &rev, staged, &what)).await?;
95    Ok(Json(json!({ "ok": true, "attachment": done })))
96}
97
98#[derive(Debug, Deserialize, Default)]
99pub struct ListQuery {
100    /// A revision id or label: its files too. Empty: the part's only.
101    #[serde(default)]
102    pub revision: String,
103}
104
105/// A part's files, and one revision's.
106pub async fn list(
107    State(db): State<Shared>,
108    headers: HeaderMap,
109    Path(id): Path<String>,
110    Query(query): Query<ListQuery>,
111) -> Result<Json<Value>, Error> {
112    require_user(&db, &headers)?;
113    db.read(|state| {
114        let part = state.part_by_id_or_number(&id).ok_or_else(|| Error::not_found("part"))?;
115        let revision = match query.revision.trim() {
116            "" => None,
117            key => Some(crate::bom::find_revision(part, key).ok_or_else(|| Error::not_found("revision"))?),
118        };
119        let name = |uid: &str| state.user(uid).map(|u| u.username.clone()).unwrap_or_default();
120        let show = |list: &[crate::model::Attachment]| -> Vec<Value> {
121            list.iter()
122                .map(|a| {
123                    let mut v = serde_json::to_value(a).unwrap_or(Value::Null);
124                    v["uploaded_by_name"] = json!(name(&a.uploaded_by));
125                    v["inline"] = json!(attach::inline_ok(&a.media_type));
126                    v
127                })
128                .collect()
129        };
130        Ok(Json(json!({
131            "part": show(&part.attachments),
132            "revision": revision.map(|r| show(&r.attachments)).unwrap_or_default(),
133            "revision_label": revision.map(|r| r.label.clone()).unwrap_or_default(),
134            "revision_editable": revision.map(|r| r.lifecycle.is_editable()).unwrap_or(false),
135            "kinds": attach::KINDS,
136        })))
137    })
138}
139
140#[derive(Debug, Deserialize, Default)]
141pub struct DownloadQuery {
142    #[serde(default)]
143    pub part: String,
144    #[serde(default)]
145    pub revision: String,
146    /// Ask to see it in the browser; honoured only for the safe types.
147    #[serde(default)]
148    pub inline: bool,
149}
150
151/// `attachment; filename=...` with an ASCII fallback and the UTF-8 name.
152fn disposition(inline: bool, name: &str) -> String {
153    let ascii: String = name
154        .chars()
155        .map(|c| if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' { c } else { '_' })
156        .collect();
157    let mut encoded = String::new();
158    for byte in name.as_bytes() {
159        if byte.is_ascii_alphanumeric() || b"-._~".contains(byte) {
160            encoded.push(*byte as char);
161        } else {
162            encoded.push_str(&format!("%{byte:02X}"));
163        }
164    }
165    format!(
166        "{}; filename=\"{ascii}\"; filename*=UTF-8''{encoded}",
167        if inline { "inline" } else { "attachment" }
168    )
169}
170
171/// Stream a file.
172pub async fn download(
173    State(db): State<Shared>,
174    headers: HeaderMap,
175    Path(id): Path<String>,
176    Query(query): Query<DownloadQuery>,
177) -> Result<Response, Error> {
178    require_user(&db, &headers)?;
179    let found = db.read(|state| attach::locate_scoped(state, &id, &query.part, &query.revision)).ok_or_else(|| Error::not_found("attachment"))?;
180    let a = found.attachment;
181    stream_blob(&db, &a.name, &a.media_type, &a.sha256, a.size, query.inline).await
182}
183
184/// Stream the blob `sha256` as a download named `name`: its media type,
185/// length, disposition (inline only when asked AND safe) and an ETag.
186/// Workspace files download the same way.
187pub(crate) async fn stream_blob(
188    db: &Shared,
189    name: &str,
190    media_type: &str,
191    sha256: &str,
192    size: u64,
193    inline: bool,
194) -> Result<Response, Error> {
195    if !attach::is_sha256(sha256) {
196        return Err(Error::internal("a file names no valid blob"));
197    }
198    let file = tokio::fs::File::open(db.blob_path(sha256))
199        .await
200        .map_err(|e| Error::internal(format!("the file for {name} is missing: {e}")))?;
201    let inline = inline && attach::inline_ok(media_type);
202    let mut response = super::body_io::file_body(file, 64 * 1024).into_response();
203    let h = response.headers_mut();
204    h.insert(
205        header::CONTENT_TYPE,
206        HeaderValue::from_str(media_type).unwrap_or(HeaderValue::from_static("application/octet-stream")),
207    );
208    h.insert(header::CONTENT_LENGTH, HeaderValue::from(size));
209    h.insert(
210        header::CONTENT_DISPOSITION,
211        HeaderValue::from_str(&disposition(inline, name)).unwrap_or(HeaderValue::from_static("attachment")),
212    );
213    if let Ok(etag) = HeaderValue::from_str(&format!("\"{sha256}\"")) {
214        h.insert(header::ETAG, etag);
215    }
216    Ok(response)
217}
218
219/// Remove an attachment.
220pub async fn remove(
221    State(db): State<Shared>,
222    headers: HeaderMap,
223    Path(id): Path<String>,
224) -> Result<Json<Value>, Error> {
225    let user = require_author(&db, &headers)?;
226    let gone = blocking(move || db.detach(&user, &id)).await?;
227    Ok(Json(json!({ "ok": true, "removed": gone.attachment.id })))
228}
229
230/// Metadata and server-computed edit permission for a document tab.
231pub async fn info(State(db): State<Shared>, headers: HeaderMap, Path(id): Path<String>, Query(query): Query<DownloadQuery>) -> Result<Json<Value>, Error> {
232    let user = require_user(&db, &headers)?;
233    db.read(|state| {
234        let found = attach::locate_scoped(state, &id, &query.part, &query.revision).ok_or_else(|| Error::not_found("attachment"))?;
235        let permission = attach::attachment_writable(state, &user, &found);
236        Ok(Json(json!({ "attachment": found.attachment, "part_id": found.part_id, "part_number": found.number,
237            "revision_id": found.revision_id, "revision_label": found.revision_label,
238            "writable": permission.is_ok(), "read_only_reason": permission.err().map(|e| e.message).unwrap_or_default() })))
239    })
240}
241
242pub async fn replace(State(db): State<Shared>, headers: HeaderMap, Path(id): Path<String>, Query(query): Query<DownloadQuery>, body: Body) -> Result<Json<Value>, Error> {
243    let user = require_author(&db, &headers)?;
244    let expected = headers.get(header::IF_MATCH).and_then(|v| v.to_str().ok()).unwrap_or("").trim_matches('"').to_string();
245    if !attach::is_sha256(&expected) { return Err(Error::bad_request("saving an attachment requires its current If-Match hash")); }
246    db.read(|state| {
247        let found = attach::locate_scoped(state, &id, &query.part, &query.revision).ok_or_else(|| Error::not_found("attachment"))?;
248        attach::attachment_writable(state, &user, &found)
249    })?;
250    let staged = receive_with_empty(&db, &headers, body, true).await?;
251    let found = blocking(move || db.replace_attachment(&user, &id, &query.part, &query.revision, &expected, staged)).await?;
252    Ok(Json(json!({ "ok": true, "attachment": found.attachment })))
253}