| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | | use super::{caller, reach, ApiError}; |
| 7 | | use crate::auth::roles::Access; |
| 8 | | use crate::db; |
| 9 | | use crate::Shared; |
| 10 | | use axum::body::Bytes; |
| 11 | | use axum::extract::{Path, Query, State}; |
| 12 | | use axum::http::{HeaderMap, StatusCode}; |
| 13 | | use axum::Json; |
| 14 | |
|
| 15 | |
|
| 16 | | pub const ATTACHMENT_MAX: usize = 25 << 20; |
| 17 | |
|
| 18 | | #[derive(serde::Deserialize)] |
| 19 | | pub struct Named { |
| 20 | | name: String, |
| 21 | | } |
| 22 | |
|
| 23 | |
|
| 24 | |
|
| 25 | 14× | pub fn image_type(bytes: &[u8]) -> Option<&'static str> { |
| 26 | 14× | if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { |
| 27 | 6× | Some("image/png") |
| 28 | 8× | } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { |
| 29 | 1× | Some("image/jpeg") |
| 30 | 7× | } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { |
| 31 | 1× | Some("image/gif") |
| 32 | 6× | } else if bytes.len() >= 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { |
| 33 | 1× | Some("image/webp") |
| 34 | | } else { |
| 35 | 5× | None |
| 36 | | } |
| 37 | 14× | } |
| 38 | |
|
| 39 | |
|
| 40 | 12× | pub fn file_name(name: &str) -> Option<String> { |
| 41 | 12× | let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim(); |
| 42 | 76× | let clean: String = base.chars().filter(|c| !c.is_control() && !matches!(c, '"' | '<' | '>' | '`')).collect(); |
| 43 | 12× | (!clean.is_empty() && !clean.starts_with('.') && clean.len() <= 200).then_some(clean) |
| 44 | 12× | } |
| 45 | |
|
| 46 | |
|
| 47 | 6× | fn seg(s: &str) -> String { |
| 48 | 6× | s.bytes() |
| 49 | 44× | .map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }) |
| 50 | 6× | .collect() |
| 51 | 6× | } |
| 52 | |
|
| 53 | 8× | pub async fn upload( |
| 54 | 8× | State(app): State<Shared>, |
| 55 | 8× | headers: HeaderMap, |
| 56 | 8× | Path((owner, name)): Path<(String, String)>, |
| 57 | 8× | Query(q): Query<Named>, |
| 58 | 8× | body: Bytes, |
| 59 | 8× | ) -> Result<(StatusCode, Json<hub_api::Attachment>), ApiError> { |
| 60 | 8× | let c = caller(&app, &headers).await?; |
| 61 | 8× | let me = c.require("issues:write").or_else(|_| c.require("repo:write"))?.clone(); |
| 62 | 7× | let (_, row, _) = reach(&app, &c, &owner, &name, Access::Read).await?; |
| 63 | 7× | let Some(file) = file_name(&q.name) else { |
| 64 | 1× | return Err(ApiError( |
| 65 | 1× | StatusCode::UNPROCESSABLE_ENTITY, |
| 66 | 1× | "give the file a name (?name=FILE): plain, not hidden, at most 200 bytes".into(), |
| 67 | 1× | )); |
| 68 | | }; |
| 69 | 6× | if body.is_empty() { |
| 70 | 0× | return Err(ApiError(StatusCode::UNPROCESSABLE_ENTITY, "the file is empty".into())); |
| 71 | 6× | } |
| 72 | 6× | if body.len() > ATTACHMENT_MAX { |
| 73 | 0× | return Err(ApiError(StatusCode::PAYLOAD_TOO_LARGE, format!("an attachment is at most {} MiB", ATTACHMENT_MAX >> 20))); |
| 74 | 6× | } |
| 75 | 6× | let image = image_type(&body); |
| 76 | 6× | let content_type = image.unwrap_or("application/octet-stream"); |
| 77 | 6× | let hash = hex::encode(blake3::hash(&body).as_bytes()); |
| 78 | 6× | let path = crate::web::releases::blob_path(&app, &hash); |
| 79 | 6× | if !path.exists() { |
| 80 | 4× | let parent = path.parent().expect("a blob is in a directory"); |
| 81 | 4× | tokio::fs::create_dir_all(parent).await.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 82 | 4× | let tmp = path.with_extension("partial"); |
| 83 | 4× | tokio::fs::write(&tmp, &body).await.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 84 | 4× | tokio::fs::rename(&tmp, &path).await.map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; |
| 85 | 2× | } |
| 86 | 6× | let a = db::attachments::add(&app.db, row.id, &file, body.len() as i64, &hash, content_type, Some(me.id)).await?; |
| 87 | 6× | let url = format!("{}/{}/{}/attachments/{}/{}", app.config.base_url().trim_end_matches('/'), row.owner, row.name, a.id, seg(&file)); |
| 88 | 6× | let markdown = if image.is_some() { format!("") } else { format!("[{file}]({url})") }; |
| 89 | 6× | Ok(( |
| 90 | 6× | StatusCode::CREATED, |
| 91 | 6× | Json(hub_api::Attachment { |
| 92 | 6× | id: a.id, |
| 93 | 6× | name: file, |
| 94 | 6× | size: a.size, |
| 95 | 6× | content_type: content_type.into(), |
| 96 | 6× | inline: image.is_some(), |
| 97 | 6× | url, |
| 98 | 6× | markdown, |
| 99 | 6× | }), |
| 100 | 6× | )) |
| 101 | 8× | } |
| 102 | |
|
| 103 | | #[cfg(test)] |
| 104 | | mod tests { |
| 105 | | use super::*; |
| 106 | |
|
| 107 | | #[test] |
| 108 | 1× | fn only_real_images_show_in_place() { |
| 109 | 1× | assert_eq!(image_type(b"\x89PNG\r\n\x1a\n...."), Some("image/png")); |
| 110 | 1× | assert_eq!(image_type(&[0xFF, 0xD8, 0xFF, 0xE0]), Some("image/jpeg")); |
| 111 | 1× | assert_eq!(image_type(b"GIF89a.."), Some("image/gif")); |
| 112 | 1× | assert_eq!(image_type(b"RIFF\0\0\0\0WEBPVP8 "), Some("image/webp")); |
| 113 | 1× | assert_eq!(image_type(b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script/></svg>"), None, "an SVG is a download"); |
| 114 | 1× | assert_eq!(image_type(b"<html><script>alert(1)</script>"), None); |
| 115 | 1× | } |
| 116 | |
|
| 117 | | #[test] |
| 118 | 1× | fn file_names_are_kept_plain() { |
| 119 | 1× | assert_eq!(file_name("C:\\Users\\a\\shot.png").as_deref(), Some("shot.png")); |
| 120 | 1× | assert_eq!(file_name("../../etc/passwd").as_deref(), Some("passwd")); |
| 121 | 1× | assert_eq!(file_name("a\"b<c>.txt").as_deref(), Some("abc.txt")); |
| 122 | 1× | assert_eq!(file_name(".env"), None); |
| 123 | 1× | assert_eq!(file_name(" "), None); |
| 124 | 1× | } |
| 125 | | } |