fix(security): batch-2 hardening — XSS allowlist, event-scoping, deploy
Address the seven findings from the security & deployment review. High: - upload: make infer authoritative — reject files it can't identify (SVG/HTML/JS) and require the detected MIME to be on an ALLOWED_MEDIA allowlist; derive the stored MIME and on-disk extension from the detected type, ignoring client filename/Content-Type. Closes the stored-XSS vector via media served on-origin. - deploy: rename docker-compose.override.yml -> docker-compose.dev.yml so the default `docker compose up -d` no longer publishes Postgres 5432 to the host; the port map is now opt-in via -f. README updated. Medium: - upload: DefaultBodyLimit::disable() -> max(576 MiB) as an HTTP-level OOM backstop; handler still enforces precise per-class size limits. - docker: run backend and frontend as non-root users. Low: - social/upload: event-scope toggle_like, list_comments, add_comment, delete_comment, edit_upload, delete_upload via find_by_id_and_event / soft_delete_in_event — cross-event IDs now resolve to 404. - Caddy: site-wide HSTS / nosniff / X-Frame-Options / Referrer-Policy, plus Content-Disposition: attachment on /media/originals/*. - .env.example: replace default Postgres password with a CHANGE_ME hint. Out of scope: localStorage JWT (root cause fixed; httpOnly cookies are a larger change tracked separately). Verified: cargo build (no new warnings), cargo test (3 passed), caddy validate, docker compose config (no 5432 published by default). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,23 @@ use crate::state::AppState;
|
||||
|
||||
const MAX_CAPTION_LENGTH: usize = 2000;
|
||||
|
||||
/// Allowlist of accepted media types, keyed by the MIME that `infer` derives from
|
||||
/// the file's magic bytes. The detected MIME (not the client-declared one) is what
|
||||
/// we trust, store, and hand to the compression pipeline — so a text-based payload
|
||||
/// (SVG/HTML/JS) can never be stored or served on-origin. Each entry maps to the
|
||||
/// server-controlled file extension we persist the original under.
|
||||
const ALLOWED_MEDIA: &[(&str, &str)] = &[
|
||||
("image/jpeg", "jpg"),
|
||||
("image/png", "png"),
|
||||
("image/webp", "webp"),
|
||||
("image/gif", "gif"),
|
||||
("image/heic", "heic"),
|
||||
("image/heif", "heif"),
|
||||
("video/mp4", "mp4"),
|
||||
("video/quicktime", "mov"),
|
||||
("video/webm", "webm"),
|
||||
];
|
||||
|
||||
pub async fn upload(
|
||||
State(state): State<AppState>,
|
||||
auth: AuthUser,
|
||||
@@ -62,8 +79,6 @@ pub async fn upload(
|
||||
let max_video_mb: i64 = config::get_i64(&state.pool, "max_video_size_mb", 500).await;
|
||||
|
||||
let mut file_data: Option<Vec<u8>> = None;
|
||||
let mut file_name: Option<String> = None;
|
||||
let mut content_type: Option<String> = None;
|
||||
let mut caption: Option<String> = None;
|
||||
let mut hashtags_csv: Option<String> = None;
|
||||
|
||||
@@ -71,8 +86,9 @@ pub async fn upload(
|
||||
let name = field.name().unwrap_or_default().to_string();
|
||||
match name.as_str() {
|
||||
"file" => {
|
||||
file_name = field.file_name().map(|s| s.to_string());
|
||||
content_type = field.content_type().map(|s| s.to_string());
|
||||
// Note: the client-declared filename and Content-Type are intentionally
|
||||
// ignored — the stored MIME and extension are derived from the file's
|
||||
// magic bytes below, so a mislabelled payload can't influence them.
|
||||
file_data = Some(
|
||||
field.bytes().await
|
||||
.map_err(|e| AppError::BadRequest(format!("Datei konnte nicht gelesen werden: {e}")))?
|
||||
@@ -96,7 +112,6 @@ pub async fn upload(
|
||||
}
|
||||
|
||||
let data = file_data.ok_or_else(|| AppError::BadRequest("Keine Datei hochgeladen.".into()))?;
|
||||
let mime = content_type.unwrap_or_else(|| "application/octet-stream".to_string());
|
||||
let size = data.len() as i64;
|
||||
|
||||
// Validate caption length. Counted in chars (code points) to match the
|
||||
@@ -111,22 +126,23 @@ pub async fn upload(
|
||||
}
|
||||
}
|
||||
|
||||
// Validate file MIME type using magic bytes
|
||||
let detected_mime = infer::get(&data);
|
||||
if let Some(detected) = detected_mime {
|
||||
let detected_type = detected.mime_type();
|
||||
// Ensure detected type is compatible with declared MIME type
|
||||
let declared_category = mime.split('/').next().unwrap_or("");
|
||||
let detected_category = detected_type.split('/').next().unwrap_or("");
|
||||
|
||||
// Only reject if categories don't match (e.g., image vs video)
|
||||
if declared_category != "application" && declared_category != detected_category {
|
||||
return Err(AppError::BadRequest(format!(
|
||||
"Dateiinhalt entspricht nicht dem deklarierten Typ. Erwartet: {}, erkannt: {}",
|
||||
mime, detected_type
|
||||
)));
|
||||
}
|
||||
}
|
||||
// Determine the file type from its magic bytes and require it to be on the
|
||||
// allowlist. `infer` returns None for text-based payloads (SVG/HTML/JS), so
|
||||
// those are rejected outright — closing the stored-XSS vector. Both the MIME
|
||||
// we persist and the on-disk extension come from the detected type, never from
|
||||
// client-supplied values.
|
||||
let kind = infer::get(&data)
|
||||
.ok_or_else(|| AppError::BadRequest("Dateityp nicht erkannt oder nicht unterstützt.".into()))?;
|
||||
let (mime, ext) = ALLOWED_MEDIA
|
||||
.iter()
|
||||
.find(|(allowed, _)| *allowed == kind.mime_type())
|
||||
.map(|(m, e)| ((*m).to_string(), *e))
|
||||
.ok_or_else(|| {
|
||||
AppError::BadRequest(format!(
|
||||
"Dateityp wird nicht unterstützt: {}.",
|
||||
kind.mime_type()
|
||||
))
|
||||
})?;
|
||||
|
||||
// Validate file size
|
||||
let max_bytes = if mime.starts_with("video/") {
|
||||
@@ -159,12 +175,6 @@ pub async fn upload(
|
||||
}
|
||||
}
|
||||
|
||||
// Determine file extension
|
||||
let ext = file_name
|
||||
.as_deref()
|
||||
.and_then(|n| n.rsplit('.').next())
|
||||
.unwrap_or(if mime.starts_with("video/") { "mp4" } else { "jpg" });
|
||||
|
||||
let upload_id = Uuid::new_v4();
|
||||
let event_slug = &state.config.event_slug;
|
||||
let relative_path = format!("originals/{event_slug}/{upload_id}.{ext}");
|
||||
@@ -257,7 +267,7 @@ pub async fn edit_upload(
|
||||
Path(upload_id): Path<Uuid>,
|
||||
Json(body): Json<EditUploadRequest>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let upload = Upload::find_by_id(&state.pool, upload_id)
|
||||
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
|
||||
@@ -285,7 +295,7 @@ pub async fn delete_upload(
|
||||
auth: AuthUser,
|
||||
Path(upload_id): Path<Uuid>,
|
||||
) -> Result<StatusCode, AppError> {
|
||||
let upload = Upload::find_by_id(&state.pool, upload_id)
|
||||
let upload = Upload::find_by_id_and_event(&state.pool, upload_id, auth.event_id)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound("Upload nicht gefunden.".into()))?;
|
||||
|
||||
@@ -293,7 +303,7 @@ pub async fn delete_upload(
|
||||
return Err(AppError::Forbidden("Nur eigene Uploads löschen.".into()));
|
||||
}
|
||||
|
||||
Upload::soft_delete(&state.pool, upload_id).await?;
|
||||
Upload::soft_delete_in_event(&state.pool, upload_id, auth.event_id).await?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user