feat(security): stream uploads end to end, bound request bodies (#258)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 7m9s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 7m9s
The second half of #258. A file upload of up to 512 MiB used to be held in memory about five times over: the browser read it into WASM memory, sent it to the dashboard as a JSON byte array inside a server function (roughly 4x the file), the dashboard copied it into a multipart request, and the agent buffered the whole field before writing it. Several concurrent uploads could exhaust an 8 GB node. Now nothing holds the file: - Browser: the wizard keeps the picked file's handle, not its bytes, and passes it as a Dioxus `FileStream`, which sends the `File` itself as the request body (browser-native streaming from disk). - Dashboard: `POST /api/uploads/{id}?kind&plc_format` forwards that body to the agent as the multipart `file` part via `reqwest::Body::wrap_stream`. - Agent: the `file` field is written to disk chunk by chunk, refused with 413 past 512 MiB, and owned by a guard that deletes it on any early return — an oversized, malformed or kind-less upload leaves nothing behind. Request bodies: the 512 MiB limit applied to every route on both services, so any JSON endpoint could be made to buffer half a gigabyte. It is now scoped: the upload route (streamed) and the runner's job-result route (32 MiB) on the agent, the webhook proxy (25 MB, GitHub's cap) on the dashboard; everything else keeps axum's 2 MiB default. Also fixes the two `manual_checked_ops` lints in `attack_chain/view.rs` that newer clippy reports, so dashboard clippy runs clean locally. Verified end to end in a real browser (agent + dashboard + Chromium): a 3 MiB firmware image went through the wizard as `application/octet-stream` with no JSON encoding and landed on disk byte-identical (SHA-256 match). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p
This commit is contained in:
1 parent
55da128a3c
commit
3a4919f0f6
10 files changed
+304
-96
No files matched your search
+1
-1
@@ -26,7 +26,7 @@ tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
|
||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies"], default-features = false }
|
||||
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
|
||||
thiserror = "2"
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
|
||||
@@ -20,6 +20,7 @@ use compliance_core::tenant_ctx::TenantCtx;
|
||||
|
||||
use crate::agent::ComplianceAgent;
|
||||
use crate::classify::{classify_target, MockFirmwareDetector};
|
||||
use crate::targets::{upload_dest, uploaded_artifact, MAX_UPLOAD_BYTES};
|
||||
|
||||
use super::dto::tenant_db;
|
||||
use super::{collect_cursor_async, ApiResponse, PaginationParams};
|
||||
@@ -376,12 +377,16 @@ pub async fn add_artifact(
|
||||
}
|
||||
|
||||
/// POST /api/v1/targets/{id}/artifacts/upload — attach an artifact by uploading
|
||||
/// its file (PLC project, firmware image, source archive, mobile package). The
|
||||
/// bytes are written to the artifact blob store and referenced by `stored_path`,
|
||||
/// so ingest resolves them locally (no URL fetch).
|
||||
/// its file (PLC project, firmware image, source archive, mobile package).
|
||||
///
|
||||
/// Multipart fields: `file` (required), `kind` (required, snake_case
|
||||
/// `ArtifactKind`), `plc_format` (optional, for PLC projects).
|
||||
/// The file is **streamed to disk** chunk by chunk as it arrives, never held in
|
||||
/// memory whole (it used to be read into one buffer of up to 512 MiB, per
|
||||
/// request), and refused with 413 past [`MAX_UPLOAD_BYTES`]. The stored path is
|
||||
/// referenced by `stored_path`, so ingest resolves it locally.
|
||||
///
|
||||
/// Multipart fields: `file` (required, exactly one), `kind` (required,
|
||||
/// snake_case `ArtifactKind`), `plc_format` (optional, for PLC projects), in
|
||||
/// any order.
|
||||
#[tracing::instrument(skip_all, fields(target_id = %id))]
|
||||
pub async fn upload_artifact(
|
||||
Extension(agent): AgentExt,
|
||||
@@ -404,69 +409,44 @@ pub async fn upload_artifact(
|
||||
let mut kind: Option<ArtifactKind> = None;
|
||||
let mut plc_format: Option<PlcFormat> = None;
|
||||
let mut filename = String::from("upload.bin");
|
||||
let mut bytes: Option<axum::body::Bytes> = None;
|
||||
// Owns the file on disk until the artifact record references it; any early
|
||||
// return below deletes it.
|
||||
let mut stored: Option<StoredUpload> = None;
|
||||
|
||||
while let Some(field) = multipart
|
||||
.next_field()
|
||||
.await
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?
|
||||
{
|
||||
while let Some(mut field) = multipart.next_field().await.map_err(|e| e.status())? {
|
||||
match field.name().unwrap_or("") {
|
||||
"kind" => {
|
||||
let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let v = field.text().await.map_err(|e| e.status())?;
|
||||
kind = parse_enum(&v);
|
||||
}
|
||||
"plc_format" => {
|
||||
let v = field.text().await.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let v = field.text().await.map_err(|e| e.status())?;
|
||||
plc_format = parse_enum(&v);
|
||||
}
|
||||
"file" => {
|
||||
if stored.is_some() {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if let Some(fname) = field.file_name() {
|
||||
filename = fname.to_string();
|
||||
}
|
||||
bytes = Some(field.bytes().await.map_err(|_| StatusCode::BAD_REQUEST)?);
|
||||
let dest = upload_dest(&agent, &id, &filename)
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut upload = StoredUpload::new(dest);
|
||||
upload.size = stream_to_disk(&mut field, &upload.path, MAX_UPLOAD_BYTES).await?;
|
||||
stored = Some(upload);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let (Some(kind), Some(bytes)) = (kind, bytes) else {
|
||||
let (Some(kind), Some(upload)) = (kind, stored) else {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
};
|
||||
|
||||
// Store the uploaded bytes under the artifact blob store.
|
||||
let safe_name: String = filename
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let dir = std::path::Path::new(&agent.config.artifact_store_base_path)
|
||||
.join("uploads")
|
||||
.join(&id);
|
||||
std::fs::create_dir_all(&dir).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let dest = dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4()));
|
||||
std::fs::write(&dest, bytes.as_ref()).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
// Build the artifact for this kind, referencing the stored file.
|
||||
let mut artifact = match kind {
|
||||
ArtifactKind::PlcProject => Artifact::plc_project(
|
||||
filename.clone(),
|
||||
plc_format.unwrap_or(PlcFormat::PlcopenXml),
|
||||
),
|
||||
ArtifactKind::FirmwareImage => Artifact::firmware_image(filename.clone()),
|
||||
ArtifactKind::SourceArchive => Artifact::source_archive(filename.clone()),
|
||||
ArtifactKind::MobilePackage => Artifact::mobile_package(filename.clone()),
|
||||
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||
// add-artifact endpoint, not upload.
|
||||
_ => return Err(StatusCode::BAD_REQUEST),
|
||||
};
|
||||
artifact.stored_path = Some(dest.to_string_lossy().to_string());
|
||||
artifact.size_bytes = Some(bytes.len() as u64);
|
||||
// Non-file kinds (git repo, live URL, container ref, text) use the JSON
|
||||
// add-artifact endpoint, not upload.
|
||||
let artifact = uploaded_artifact(kind, plc_format, &filename, &upload.path, upload.size)
|
||||
.ok_or(StatusCode::BAD_REQUEST)?;
|
||||
|
||||
let artifact_bson = to_bson(&artifact).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
db.onboarded_targets()
|
||||
@@ -476,10 +456,76 @@ pub async fn upload_artifact(
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
upload.keep();
|
||||
|
||||
get_target(Extension(agent), tenant, Path(id)).await
|
||||
}
|
||||
|
||||
/// Write one multipart field to `dest` as its chunks arrive, refusing more than
|
||||
/// `max` bytes. Returns the number of bytes written.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 413 past `max`, the multipart error's own status for a malformed or
|
||||
/// over-limit body, 500 if the file cannot be written.
|
||||
async fn stream_to_disk(
|
||||
field: &mut axum::extract::multipart::Field<'_>,
|
||||
dest: &std::path::Path,
|
||||
max: u64,
|
||||
) -> Result<u64, StatusCode> {
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
let mut file = tokio::fs::File::create(dest)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
let mut written: u64 = 0;
|
||||
while let Some(chunk) = field.chunk().await.map_err(|e| e.status())? {
|
||||
written += chunk.len() as u64;
|
||||
if written > max {
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
file.write_all(&chunk)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
}
|
||||
file.flush()
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// An uploaded file on disk that is deleted when dropped, unless [`Self::keep`]
|
||||
/// is called once the artifact record references it. This is what stops a
|
||||
/// rejected, oversized or half-received upload from being left on disk.
|
||||
struct StoredUpload {
|
||||
path: std::path::PathBuf,
|
||||
size: u64,
|
||||
keep: bool,
|
||||
}
|
||||
|
||||
impl StoredUpload {
|
||||
fn new(path: std::path::PathBuf) -> Self {
|
||||
Self {
|
||||
path,
|
||||
size: 0,
|
||||
keep: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The artifact now references this file; leave it in place.
|
||||
fn keep(mut self) {
|
||||
self.keep = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for StoredUpload {
|
||||
fn drop(&mut self) {
|
||||
if !self.keep {
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deserialize a snake_case enum value from a plain string.
|
||||
fn parse_enum<T: for<'de> Deserialize<'de>>(s: &str) -> Option<T> {
|
||||
serde_json::from_value(serde_json::Value::String(s.to_string())).ok()
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
use axum::extract::DefaultBodyLimit;
|
||||
use axum::routing::{delete, get, patch, post};
|
||||
use axum::Router;
|
||||
|
||||
use crate::api::handlers;
|
||||
|
||||
/// Allowance on top of the file itself for the multipart framing: boundaries,
|
||||
/// part headers and the small `kind` / `plc_format` text fields.
|
||||
const MULTIPART_OVERHEAD: usize = 1024 * 1024;
|
||||
|
||||
pub fn build_router() -> Router {
|
||||
Router::new()
|
||||
.route("/api/v1/health", get(handlers::health))
|
||||
@@ -32,7 +37,12 @@ pub fn build_router() -> Router {
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/artifacts/upload",
|
||||
post(handlers::onboarding::upload_artifact),
|
||||
// The one route that takes large bodies — and it streams them to
|
||||
// disk. Every other route keeps axum's 2 MiB default, so a JSON
|
||||
// endpoint can no longer be sent a 512 MiB body to buffer.
|
||||
post(handlers::onboarding::upload_artifact).layer(DefaultBodyLimit::max(
|
||||
crate::targets::MAX_UPLOAD_BYTES as usize + MULTIPART_OVERHEAD,
|
||||
)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/targets/{id}/applicable-scans",
|
||||
|
||||
@@ -26,6 +26,10 @@ use crate::error::AgentError;
|
||||
/// just to poke at the API. Override via `DEV_TENANT_ID`.
|
||||
const DEFAULT_DEV_TENANT_ID: &str = "dev";
|
||||
|
||||
/// Largest job result a Werkbank runner may post. Every other JSON route keeps
|
||||
/// axum's 2 MiB default; only uploads (streamed) and this one go higher.
|
||||
const RUNNER_RESULT_MAX_BYTES: usize = 32 * 1024 * 1024;
|
||||
|
||||
/// Inject a synthetic [`TenantContext`] for any request that lacks one.
|
||||
/// Only mounted when Keycloak is NOT configured; with KC, the real
|
||||
/// `require_jwt_auth` middleware owns this and we never reach here
|
||||
@@ -236,7 +240,10 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
)
|
||||
.route(
|
||||
"/api/v1/werkbank/jobs/complete",
|
||||
post(handlers::werkbank_jobs::complete),
|
||||
// A job's result carries all its findings as JSON, which can
|
||||
// outgrow the 2 MiB default. The route is behind a runner key.
|
||||
post(handlers::werkbank_jobs::complete)
|
||||
.layer(DefaultBodyLimit::max(RUNNER_RESULT_MAX_BYTES)),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/werkbank/jobs/enqueue",
|
||||
@@ -257,9 +264,6 @@ pub async fn start_api_server(agent: ComplianceAgent, port: u16) -> Result<(), A
|
||||
.merge(admin_router)
|
||||
.merge(werkbank_router)
|
||||
.merge(platform_router)
|
||||
// Allow large artifact uploads (PLC .projectarchive, firmware images,
|
||||
// mobile packages) — axum's default request-body limit is only 2 MiB.
|
||||
.layer(DefaultBodyLimit::max(512 * 1024 * 1024))
|
||||
.layer(Extension(shared.clone()))
|
||||
.layer(cors_layer(
|
||||
&agent.config.cors_allowed_origins,
|
||||
|
||||
@@ -36,13 +36,19 @@ pub async fn create_target(
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
/// Write uploaded bytes into the artifact blob store under
|
||||
/// `<base>/uploads/<target_id>/<uuid>_<safe filename>` and return the path.
|
||||
pub fn store_upload(
|
||||
/// Largest file one upload may carry.
|
||||
pub const MAX_UPLOAD_BYTES: u64 = 512 * 1024 * 1024;
|
||||
|
||||
/// Where an uploaded file for `target_id` goes:
|
||||
/// `<base>/uploads/<target_id>/<uuid>_<safe filename>`. Creates the directory.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the upload directory cannot be created.
|
||||
pub fn upload_dest(
|
||||
agent: &ComplianceAgent,
|
||||
target_id: &str,
|
||||
filename: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<PathBuf, AgentError> {
|
||||
let safe_name: String = filename
|
||||
.chars()
|
||||
@@ -58,7 +64,22 @@ pub fn store_upload(
|
||||
.join("uploads")
|
||||
.join(target_id);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let dest = dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4()));
|
||||
Ok(dir.join(format!("{}_{safe_name}", uuid::Uuid::new_v4())))
|
||||
}
|
||||
|
||||
/// Write bytes that are already in memory (the bundled demo fixtures) to their
|
||||
/// upload location and return the path. User uploads are streamed instead.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error if the directory or the file cannot be written.
|
||||
pub fn store_upload(
|
||||
agent: &ComplianceAgent,
|
||||
target_id: &str,
|
||||
filename: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<PathBuf, AgentError> {
|
||||
let dest = upload_dest(agent, target_id, filename)?;
|
||||
std::fs::write(&dest, bytes)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
@@ -113,3 +113,112 @@ async fn add_artifact_and_delete_target() {
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
/// Create an empty firmware target and return its id.
|
||||
async fn firmware_target(server: &TestServer, name: &str) -> String {
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({ "name": name, "target_type": "firmware_bare_metal", "artifacts": [] }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
body["data"]["_id"]["$oid"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Files under the upload directory of `target_id`.
|
||||
fn stored_uploads(target_id: &str) -> Vec<std::path::PathBuf> {
|
||||
let dir = std::path::Path::new("/tmp/compliance-scanner-tests/artifacts")
|
||||
.join("uploads")
|
||||
.join(target_id);
|
||||
std::fs::read_dir(dir)
|
||||
.map(|entries| entries.filter_map(|e| e.ok().map(|e| e.path())).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_upload_larger_than_the_json_limit_is_streamed_to_disk() {
|
||||
let server = TestServer::start().await;
|
||||
let id = firmware_target(&server, "fw-upload").await;
|
||||
|
||||
// 3 MiB: over axum's 2 MiB default, so it only works on the upload
|
||||
// route's own limit, and it is written as it arrives.
|
||||
let payload = vec![0xA5_u8; 3 * 1024 * 1024];
|
||||
let form = reqwest::multipart::Form::new()
|
||||
.text("kind", "firmware_image")
|
||||
.part(
|
||||
"file",
|
||||
reqwest::multipart::Part::bytes(payload.clone()).file_name("fw.bin"),
|
||||
);
|
||||
let resp = server
|
||||
.client
|
||||
.post(format!(
|
||||
"{}/api/v1/targets/{id}/artifacts/upload",
|
||||
server.base_url
|
||||
))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), 200);
|
||||
let body: serde_json::Value = resp.json().await.unwrap();
|
||||
let artifacts = body["data"]["artifacts"].as_array().unwrap();
|
||||
assert_eq!(artifacts.len(), 1);
|
||||
assert_eq!(artifacts[0]["size_bytes"], payload.len() as u64);
|
||||
|
||||
let files = stored_uploads(&id);
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(std::fs::read(&files[0]).unwrap(), payload);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_ordinary_json_route_no_longer_accepts_a_huge_body() {
|
||||
let server = TestServer::start().await;
|
||||
// A 3 MiB description on a JSON route: it used to be buffered under a
|
||||
// 512 MiB limit that applied to every route.
|
||||
let resp = server
|
||||
.post(
|
||||
"/api/v1/targets",
|
||||
&json!({
|
||||
"name": "too-big",
|
||||
"target_type": "web_app",
|
||||
"description": "x".repeat(3 * 1024 * 1024),
|
||||
"artifacts": []
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(resp.status(), 413);
|
||||
server.cleanup().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rejected_upload_leaves_no_file_behind() {
|
||||
let server = TestServer::start().await;
|
||||
let id = firmware_target(&server, "fw-reject").await;
|
||||
|
||||
// No `kind` field: refused only after the file was already streamed.
|
||||
let form = reqwest::multipart::Form::new().part(
|
||||
"file",
|
||||
reqwest::multipart::Part::bytes(vec![1_u8; 1024]).file_name("fw.bin"),
|
||||
);
|
||||
let resp = server
|
||||
.client
|
||||
.post(format!(
|
||||
"{}/api/v1/targets/{id}/artifacts/upload",
|
||||
server.base_url
|
||||
))
|
||||
.multipart(form)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), 400);
|
||||
assert!(
|
||||
stored_uploads(&id).is_empty(),
|
||||
"the partial upload must be deleted"
|
||||
);
|
||||
|
||||
server.cleanup().await;
|
||||
}
|
||||
@@ -42,11 +42,8 @@ pub fn AttackChainView(
|
||||
.filter(|s| s.get("status").and_then(|v| v.as_str()) == Some("failed"))
|
||||
.count();
|
||||
let finished = completed_count + failed_count;
|
||||
let success_pct = if finished == 0 {
|
||||
100
|
||||
} else {
|
||||
(completed_count * 100) / finished
|
||||
};
|
||||
// No finished steps yet counts as 100% successful.
|
||||
let success_pct = (completed_count * 100).checked_div(finished).unwrap_or(100);
|
||||
let max_risk: u8 = steps
|
||||
.iter()
|
||||
.filter_map(|s| s.get("risk_score").and_then(|v| v.as_u64()))
|
||||
@@ -54,11 +51,9 @@ pub fn AttackChainView(
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
let progress_pct = if total_tools == 0 {
|
||||
0
|
||||
} else {
|
||||
((completed_count + failed_count) * 100) / total_tools
|
||||
};
|
||||
let progress_pct = ((completed_count + failed_count) * 100)
|
||||
.checked_div(total_tools)
|
||||
.unwrap_or(0);
|
||||
|
||||
// Build phase data for rail and accordion
|
||||
let phase_data: Vec<PhaseData<'_>> = phases
|
||||
|
||||
@@ -258,19 +258,28 @@ pub async fn create_target(
|
||||
}
|
||||
|
||||
/// Upload a file artifact (PLC project, firmware image, source archive, mobile
|
||||
/// package) to a target — proxied to the agent as multipart.
|
||||
#[server]
|
||||
/// package) to a target, **streamed end to end**.
|
||||
///
|
||||
/// The browser sends the file itself as the request body (`FileStream` uses the
|
||||
/// `Blob`/`ReadableStream` path, so the file is never copied into WASM memory),
|
||||
/// and this function forwards that stream to the agent as the multipart `file`
|
||||
/// part chunk by chunk. It used to travel as a JSON byte array, roughly four
|
||||
/// times the file size in memory here, and was then copied again for the
|
||||
/// multipart request. `kind` and `plc_format` ride in the query string because
|
||||
/// the body is the file.
|
||||
#[post("/api/uploads/{id}?kind&plc_format")]
|
||||
pub async fn upload_target_artifact(
|
||||
id: String,
|
||||
kind: String,
|
||||
plc_format: Option<String>,
|
||||
filename: String,
|
||||
bytes: Vec<u8>,
|
||||
file: dioxus::fullstack::FileStream,
|
||||
) -> Result<TargetResponse, ServerFnError> {
|
||||
let mut form = reqwest::multipart::Form::new().text("kind", kind).part(
|
||||
"file",
|
||||
reqwest::multipart::Part::bytes(bytes).file_name(filename),
|
||||
);
|
||||
let filename = file.file_name().to_string();
|
||||
let part =
|
||||
reqwest::multipart::Part::stream(reqwest::Body::wrap_stream(file)).file_name(filename);
|
||||
let mut form = reqwest::multipart::Form::new()
|
||||
.text("kind", kind)
|
||||
.part("file", part);
|
||||
if let Some(pf) = plc_format {
|
||||
form = form.text("plc_format", pf);
|
||||
}
|
||||
@@ -283,6 +292,12 @@ pub async fn upload_target_artifact(
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(ServerFnError::new(match resp.status().as_u16() {
|
||||
413 => "file is larger than the 512 MiB upload limit".to_string(),
|
||||
code => format!("upload rejected by the agent ({code})"),
|
||||
}));
|
||||
}
|
||||
resp.json()
|
||||
.await
|
||||
.map_err(|e| ServerFnError::new(e.to_string()))
|
||||
|
||||
@@ -16,6 +16,10 @@ use super::keycloak_config::KeycloakConfig;
|
||||
use super::server_state::{ServerState, ServerStateInner};
|
||||
use super::{auth_callback, auth_login, logout, require_auth, PendingOAuthStore};
|
||||
|
||||
/// Largest webhook payload forwarded to the agent (GitHub caps push payloads at
|
||||
/// 25 MB). Every other route keeps axum's 2 MiB default.
|
||||
const WEBHOOK_MAX_BYTES: usize = 25 * 1024 * 1024;
|
||||
|
||||
pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
tokio::runtime::Runtime::new()
|
||||
.map_err(|e| DashboardError::Other(e.to_string()))?
|
||||
@@ -87,12 +91,16 @@ pub fn server_start(app: fn() -> Element) -> Result<(), DashboardError> {
|
||||
.route("/auth", get(auth_login))
|
||||
.route("/auth/callback", get(auth_callback))
|
||||
.route("/logout", get(logout))
|
||||
// Webhook proxy: forward to agent (no auth required)
|
||||
.route("/webhook/{platform}/{repo_id}", post(webhook_proxy))
|
||||
// Webhook proxy: forward to agent (no auth required). Push
|
||||
// payloads can reach 25 MB (GitHub's cap), over the 2 MiB default.
|
||||
.route(
|
||||
"/webhook/{platform}/{repo_id}",
|
||||
post(webhook_proxy).layer(DefaultBodyLimit::max(WEBHOOK_MAX_BYTES)),
|
||||
)
|
||||
.serve_dioxus_application(ServeConfig::new(), app)
|
||||
// Allow large artifact uploads through the upload server function
|
||||
// (PLC .projectarchive, firmware, mobile) — default is 2 MiB.
|
||||
.layer(DefaultBodyLimit::max(512 * 1024 * 1024))
|
||||
// No raised body limit: uploads stream through `FileStream`, which
|
||||
// reads the raw body, so every other server function keeps axum's
|
||||
// 2 MiB default instead of accepting 512 MiB JSON.
|
||||
.layer(Extension(PendingOAuthStore::default()))
|
||||
.layer(middleware::from_fn(require_auth))
|
||||
.layer(Extension(server_state))
|
||||
|
||||
@@ -60,12 +60,15 @@ fn is_file_kind(kind: &str) -> bool {
|
||||
}
|
||||
|
||||
/// A file artifact staged in the wizard, uploaded after the target is created.
|
||||
#[derive(Clone, PartialEq)]
|
||||
/// A file staged in the wizard. It holds the browser's file handle, not its
|
||||
/// contents: the file is streamed straight from disk when it is uploaded, so a
|
||||
/// 500 MB firmware image is never copied into WASM memory.
|
||||
#[derive(Clone)]
|
||||
struct PendingFile {
|
||||
kind: String,
|
||||
plc_format: Option<String>,
|
||||
filename: String,
|
||||
bytes: Vec<u8>,
|
||||
file: dioxus::html::FileData,
|
||||
}
|
||||
|
||||
/// One row in the applicable-scans list on the success step.
|
||||
@@ -135,7 +138,7 @@ pub fn OnboardingPage() -> Element {
|
||||
let mut new_branch = use_signal(|| "main".to_string());
|
||||
// File-upload artifacts (PLC project, firmware image, ...).
|
||||
let mut new_plc_format = use_signal(|| "plcopen_xml".to_string());
|
||||
let mut new_file = use_signal(|| Option::<(String, Vec<u8>)>::None);
|
||||
let mut new_file = use_signal(|| Option::<(String, dioxus::html::FileData)>::None);
|
||||
let mut pending_files = use_signal(Vec::<PendingFile>::new);
|
||||
|
||||
// Create + result state.
|
||||
@@ -318,11 +321,9 @@ pub fn OnboardingPage() -> Element {
|
||||
} else if lname.ends_with(".st") || lname.ends_with(".exp") || lname.ends_with(".scl") {
|
||||
new_plc_format.set("structured_text".to_string());
|
||||
}
|
||||
spawn(async move {
|
||||
if let Ok(bytes) = file.read_bytes().await {
|
||||
new_file.set(Some((name, bytes.to_vec())));
|
||||
}
|
||||
});
|
||||
// Keep the handle only; the bytes are read
|
||||
// (streamed) at upload time.
|
||||
new_file.set(Some((name, file)));
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -365,7 +366,7 @@ pub fn OnboardingPage() -> Element {
|
||||
kind,
|
||||
plc_format,
|
||||
filename: fname,
|
||||
bytes: data,
|
||||
file: data,
|
||||
});
|
||||
new_file.set(None);
|
||||
}
|
||||
@@ -417,7 +418,7 @@ pub fn OnboardingPage() -> Element {
|
||||
if is_file_kind(&new_kind()) {
|
||||
if let Some((fname, data)) = new_file() {
|
||||
div { style: "font-size: 0.85em; opacity: 0.7; margin-top: 6px;",
|
||||
"Selected: {fname} ({data.len()} bytes)"
|
||||
"Selected: {fname} ({data.size()} bytes)"
|
||||
}
|
||||
}
|
||||
} else if let Some(err) = new_source_error.clone() {
|
||||
@@ -429,7 +430,7 @@ pub fn OnboardingPage() -> Element {
|
||||
style: "display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border: 1px solid var(--border, #333); border-radius: 6px; margin-top: 6px;",
|
||||
span {
|
||||
span { style: "opacity: 0.7;", "{kind_label(&pf.kind)} (file): " }
|
||||
"{pf.filename} ({pf.bytes.len()} bytes)"
|
||||
"{pf.filename} ({pf.file.size()} bytes)"
|
||||
}
|
||||
button {
|
||||
class: "btn btn-ghost-danger btn-sm",
|
||||
@@ -648,8 +649,7 @@ pub fn OnboardingPage() -> Element {
|
||||
id.clone(),
|
||||
pf.kind,
|
||||
pf.plc_format,
|
||||
pf.filename,
|
||||
pf.bytes,
|
||||
pf.file.into(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user