|
| 1 | +use crate::app::{ScanError, ScanService}; |
| 2 | +use crate::domain::{ScanProfileInput, ScanRequest}; |
| 3 | +use axum::extract::{Multipart, State}; |
| 4 | +use axum::http::StatusCode; |
| 5 | +use axum::response::IntoResponse; |
| 6 | +use serde_json::json; |
| 7 | +use std::io::Write; |
| 8 | +use tempfile::NamedTempFile; |
| 9 | +use tracing::info; |
| 10 | + |
| 11 | +pub async fn health() -> impl IntoResponse { |
| 12 | + StatusCode::OK |
| 13 | +} |
| 14 | + |
| 15 | +pub async fn scan_bundle( |
| 16 | + State(service): State<ScanService>, |
| 17 | + mut multipart: Multipart, |
| 18 | +) -> impl IntoResponse { |
| 19 | + let mut request = ScanRequest { profile: None }; |
| 20 | + let mut temp_file: Option<NamedTempFile> = None; |
| 21 | + |
| 22 | + while let Ok(Some(field)) = multipart.next_field().await { |
| 23 | + let name = field.name().unwrap_or_default().to_string(); |
| 24 | + if name == "profile" { |
| 25 | + if let Ok(value) = field.text().await { |
| 26 | + request.profile = match value.to_lowercase().as_str() { |
| 27 | + "basic" => Some(ScanProfileInput::Basic), |
| 28 | + "full" => Some(ScanProfileInput::Full), |
| 29 | + _ => None, |
| 30 | + }; |
| 31 | + } |
| 32 | + continue; |
| 33 | + } |
| 34 | + |
| 35 | + if name == "bundle" { |
| 36 | + let mut file = match NamedTempFile::new() { |
| 37 | + Ok(file) => file, |
| 38 | + Err(err) => return to_error(err).into_response(), |
| 39 | + }; |
| 40 | + let bytes = match field.bytes().await { |
| 41 | + Ok(bytes) => bytes, |
| 42 | + Err(err) => return to_error(err).into_response(), |
| 43 | + }; |
| 44 | + if let Err(err) = file.write_all(&bytes) { |
| 45 | + return to_error(err).into_response(); |
| 46 | + } |
| 47 | + temp_file = Some(file); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + let Some(bundle) = temp_file else { |
| 52 | + return ( |
| 53 | + StatusCode::BAD_REQUEST, |
| 54 | + json!({ "error": "missing bundle file field" }), |
| 55 | + ) |
| 56 | + .into_response(); |
| 57 | + }; |
| 58 | + |
| 59 | + info!("running scan for uploaded bundle"); |
| 60 | + match service.run_scan(request, bundle.path()) { |
| 61 | + Ok(result) => ( |
| 62 | + StatusCode::OK, |
| 63 | + serde_json::to_value(result).unwrap_or_default(), |
| 64 | + ) |
| 65 | + .into_response(), |
| 66 | + Err(err) => (StatusCode::BAD_REQUEST, error_body(err)).into_response(), |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +fn error_body(err: ScanError) -> serde_json::Value { |
| 71 | + json!({ "error": err.to_string() }) |
| 72 | +} |
| 73 | + |
| 74 | +fn to_error(err: impl std::fmt::Display) -> (StatusCode, serde_json::Value) { |
| 75 | + (StatusCode::BAD_REQUEST, json!({ "error": err.to_string() })) |
| 76 | +} |
0 commit comments