diff --git a/crucible-kueue/src/manifest.rs b/crucible-kueue/src/manifest.rs index 345e38783..81b9b0a71 100644 --- a/crucible-kueue/src/manifest.rs +++ b/crucible-kueue/src/manifest.rs @@ -1649,6 +1649,12 @@ fn check_pod_spec( fn check_volume(vol: &Value, path: &str, cfg: &Config) -> Result<(), ManifestError> { let lists = &cfg.profile.lists; let vol = object_at(vol, path)?; + if vol.get("name").and_then(Value::as_str) == Some(crate::collector::NAME) { + return Err(forbidden( + format!("{path}/name"), + "the name crucible-results, which the results collector takes,", + )); + } let mut source_count = 0usize; for k in vol.keys().filter(|k| k.as_str() != "name") { if !lists.volume_sources.contains(k) { @@ -1709,6 +1715,12 @@ fn check_volume(vol: &Value, path: &str, cfg: &Config) -> Result<(), ManifestErr fn check_container(c: &Value, path: &str, cfg: &Config) -> Result<(), ManifestError> { let lists = &cfg.profile.lists; let c = object_at(c, path)?; + if c.get("name").and_then(Value::as_str) == Some(crate::collector::NAME) { + return Err(forbidden( + format!("{path}/name"), + "the name crucible-results, which the results collector takes,", + )); + } only_fields(c, &lists.container, path)?; if let Some(env) = c.get("env") { for (i, e) in array_of(env, &format!("{path}/env"))?.iter().enumerate() { @@ -1932,7 +1944,7 @@ fn container_requests( path: format!("{path}/resources/{source}/{k}"), value: text.clone(), })?; - if q < crate::quantity::zero() { + if !crate::quantity::in_bounds(&q) { return Err(ManifestError::Quantity { path: format!("{path}/resources/{source}/{k}"), value: text, @@ -3847,4 +3859,38 @@ mod tests { refused_with(m, field); } } + + #[test] + fn huge_and_extreme_scale_quantities_are_refused_without_panicking() { + for (a, b) in [ + ( + "50000000000000000000000000000", + "50000000000000000000000000000", + ), + ("100Ei", "1n"), + ] { + let mut m = job(); + m["spec"]["template"]["spec"]["containers"] = json!([ + {"name": "a", "image": "img", "resources": {"requests": {"memory": a}}}, + {"name": "b", "image": "img", "resources": {"requests": {"memory": b}}}, + ]); + assert!(matches!( + normalize(m, &caller(), &queue(), &Config::default()), + Err(ManifestError::Quantity { .. }) + )); + } + } + + #[test] + fn collector_name_is_reserved_even_without_results() { + let mut init = job(); + init["spec"]["template"]["spec"]["initContainers"] = + json!([{"name": "crucible-results", "image": "busybox"}]); + refused_with(init, "crucible-results"); + + let mut vol = job(); + vol["spec"]["template"]["spec"]["volumes"] = + json!([{"name": "crucible-results", "emptyDir": {}}]); + refused_with(vol, "crucible-results"); + } } diff --git a/crucible-kueue/src/quantity.rs b/crucible-kueue/src/quantity.rs index 7bc8f3b26..4e4ebabc9 100644 --- a/crucible-kueue/src/quantity.rs +++ b/crucible-kueue/src/quantity.rs @@ -7,6 +7,14 @@ pub fn zero() -> ParsedQuantity { ParsedQuantity::try_from("0").unwrap_or_default() } +pub fn max_request() -> ParsedQuantity { + ParsedQuantity::try_from("100Ti").unwrap_or_default() +} + +pub fn in_bounds(q: &ParsedQuantity) -> bool { + *q >= zero() && *q <= max_request() +} + pub fn serialize(q: &ParsedQuantity, s: S) -> Result { s.serialize_str(&q.to_string()) } diff --git a/crucible-kueue/src/results.rs b/crucible-kueue/src/results.rs index a57a41166..bfcbe4649 100644 --- a/crucible-kueue/src/results.rs +++ b/crucible-kueue/src/results.rs @@ -81,16 +81,19 @@ struct Found { bytes: u64, } +const MAX_DEPTH: usize = 64; + #[derive(Default)] struct Walk { files: Vec, unread: Vec, + dirs_visited: usize, overflowed: bool, } impl Walk { fn full(&mut self) -> bool { - if self.files.len() + self.unread.len() >= MAX_FILES { + if self.files.len() + self.unread.len() >= MAX_FILES || self.dirs_visited >= MAX_FILES { self.overflowed = true; } self.overflowed @@ -103,7 +106,12 @@ impl Walk { }); } - fn visit(&mut self, dir: &Path, prefix: &str) { + fn visit(&mut self, dir: &Path, prefix: &str, depth: usize) { + if depth >= MAX_DEPTH || self.full() { + self.overflowed = true; + return; + } + self.dirs_visited += 1; let shown = || match prefix { "" => ".".to_string(), p => p.to_string(), @@ -129,7 +137,7 @@ impl Walk { let full = entry.path(); match fs::symlink_metadata(&full) { Err(e) => self.unread(path, e), - Ok(meta) if meta.is_dir() => self.visit(&full, &path), + Ok(meta) if meta.is_dir() => self.visit(&full, &path, depth + 1), Ok(meta) if meta.is_file() => match File::open(&full) { Ok(_) => self.files.push(Found { path, @@ -215,7 +223,7 @@ fn archive(files: &[Found], out: &mut impl Write) -> io::Result<(String, u64)> { /// total at most `limit` bytes. An archive that breaks off is an error, after its record. pub fn write(dir: &Path, limit: u64, out: &mut impl Write) -> io::Result<()> { let mut walk = Walk::default(); - walk.visit(dir, ""); + walk.visit(dir, "", 0); for found in &walk.files { record( out, @@ -395,8 +403,12 @@ impl Reader { let mut tar = tar::Archive::new(GzDecoder::new(self.archive.as_slice()).take(self.tar_cap())); let mut out = Vec::new(); + let mut total: u64 = 0; for entry in tar.entries().map_err(unpack)? { - let mut entry = entry.map_err(unpack)?; + if out.len() >= MAX_FILES { + return Err(Damaged::Unpack("too many files in archive".into())); + } + let entry = entry.map_err(unpack)?; let path = entry .path() .map_err(unpack)? @@ -406,8 +418,15 @@ impl Reader { if !entry.header().entry_type().is_file() || !confined(&path) { return Err(Damaged::Path(path)); } + let remaining = self.limit.saturating_sub(total); let mut data = Vec::new(); - entry.read_to_end(&mut data).map_err(unpack)?; + let mut limited = entry.take(remaining.saturating_add(1)); + limited.read_to_end(&mut data).map_err(unpack)?; + let len = u64::try_from(data.len()).unwrap_or(u64::MAX); + total = total.saturating_add(len); + if total > self.limit { + return Err(Damaged::Unpack("archive exceeds size limit".into())); + } out.push((path, data)); } Ok(out) @@ -671,4 +690,14 @@ mod tests { "{\"results\":\"file\",\"path\":\"a\\nb\",\"bytes\":3}\n" ); } + + #[test] + fn unpack_refuses_archive_exceeding_byte_limit() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("big.bin"), vec![b'a'; 128]).unwrap(); + let log = collected(dir.path(), 1024); + let reader = read(&log, 64).unwrap(); + assert_eq!(reader.state, State::Complete); + assert!(matches!(reader.unpack(), Err(Damaged::Unpack(_)))); + } } diff --git a/crucible-kueue/src/server.rs b/crucible-kueue/src/server.rs index 5e9115a3e..de32b8330 100644 --- a/crucible-kueue/src/server.rs +++ b/crucible-kueue/src/server.rs @@ -2747,6 +2747,8 @@ impl KueueMcp { } } +const MAX_PAGED_LOG_OFFSET: usize = 64 * 1024 * 1024; + impl KueueMcp { async fn log_page( &self, @@ -2760,10 +2762,20 @@ impl KueueMcp { let failed = |source| KubeError::api("read logs of", name.to_string(), source); lp.limit_bytes = Some(req.limit_bytes); let api: Api = Api::namespaced(self.client.clone(), ns); - let stream = api.log_stream(name, &lp).await.map_err(failed)?; - let read = read_log_page(stream, req) - .await - .map_err(|e| failed(kube::Error::ReadEvents(e)))?; + let timeout = Duration::from_secs(MAX_WAIT_SECONDS); + let read = tokio::time::timeout(timeout, async { + let stream = api.log_stream(name, &lp).await.map_err(failed)?; + read_log_page(stream, req) + .await + .map_err(|e| failed(kube::Error::ReadEvents(e))) + }) + .await + .map_err(|_| { + failed(kube::Error::ReadEvents(std::io::Error::new( + std::io::ErrorKind::TimedOut, + "timed out reading log page", + ))) + })??; let mut body = json!({ "pod": name, "role": report::role(kind, pod), @@ -2800,6 +2812,8 @@ fn log_page_request(args: &LogArgs) -> Result, ToolError> { "drop since_seconds, or use since_time" } else if args.follow_seconds.is_some() { "drop follow_seconds" + } else if offset > MAX_PAGED_LOG_OFFSET { + "offset exceeds the 64 MiB paging limit; use tail_lines or since_time" } else { let page = log_budget(args.max_bytes); let limit_bytes = offset @@ -2890,16 +2904,20 @@ async fn follow_log( until: tokio::time::Instant, ) -> Result { use futures_util::AsyncReadExt; + use std::collections::VecDeque; let cap = usize::try_from(MAX_LOG_BYTES).unwrap_or(usize::MAX); - let stream = api.log_stream(pod, lp).await?; + let Ok(stream) = tokio::time::timeout_at(until, api.log_stream(pod, lp)).await else { + return Ok(String::new()); + }; + let stream = stream?; let mut stream = std::pin::pin!(stream); - let mut kept: Vec = Vec::new(); + let mut kept: VecDeque = VecDeque::new(); let mut chunk = vec![0u8; 16 * 1024]; loop { match tokio::time::timeout_at(until, stream.read(&mut chunk)).await { Err(_) | Ok(Ok(0)) => break, Ok(Ok(n)) => { - kept.extend_from_slice(&chunk[..n]); + kept.extend(&chunk[..n]); if kept.len() > cap { kept.drain(..kept.len() - cap); } @@ -2910,7 +2928,8 @@ async fn follow_log( } } } - Ok(String::from_utf8_lossy(&kept).into_owned()) + let slice = kept.make_contiguous(); + Ok(String::from_utf8_lossy(slice).into_owned()) } fn duration(seconds: i64) -> String { @@ -4102,7 +4121,8 @@ mod tests { assert_eq!(refused(json!({"tail_lines": 5})), "drop tail_lines"); assert!(refused(json!({"since_seconds": 5})).contains("since_time")); assert_eq!(refused(json!({"follow_seconds": 5})), "drop follow_seconds"); - assert!(refused(json!({"offset": usize::MAX})).contains("previous answer")); + assert!(refused(json!({"offset": MAX_PAGED_LOG_OFFSET + 1})).contains("64 MiB")); + assert!(refused(json!({"offset": usize::MAX})).contains("64 MiB")); assert_eq!( log_page_request(&args( json!({"since_time": "2026-01-01T00:00:00Z", "max_bytes": 1 << 30}) diff --git a/crucible-kueue/src/server/results.rs b/crucible-kueue/src/server/results.rs index 6d9f23256..48efdd457 100644 --- a/crucible-kueue/src/server/results.rs +++ b/crucible-kueue/src/server/results.rs @@ -175,35 +175,51 @@ impl KueueMcp { ..LogParams::default() }; let api: Api = Api::namespaced(self.client.clone(), ns); - let stream = api - .log_stream(name, &lp) - .await - .map_err(|source| KubeError::api("read the results of", name.to_string(), source))?; - let mut lines = stream.lines(); + let timeout = std::time::Duration::from_secs(crate::server::MAX_WAIT_SECONDS); let mut reader = Reader::new(collector.max_bytes); let mut damage = None; - while let Some(line) = lines.next().await { - let read = match line { - Ok(line) => reader.line(&line).map_err(|e| e.to_string()), - Err(e) => Err(format!("reading the collector's log: {e}")), - }; - if let Err(e) = read { - damage = Some(e); - break; - } - if reader.ended() || (!read_all && reader.listed()) { - break; + let streamed = tokio::time::timeout(timeout, async { + let stream = api.log_stream(name, &lp).await.map_err(|source| { + KubeError::api("read the results of", name.to_string(), source) + })?; + let mut lines = stream.lines(); + while let Some(line) = lines.next().await { + let read = match line { + Ok(line) => reader.line(&line).map_err(|e| e.to_string()), + Err(e) => Err(format!("reading the collector's log: {e}")), + }; + if let Err(e) = read { + damage = Some(e); + break; + } + if reader.ended() || (!read_all && reader.listed()) { + break; + } } + Ok::<(), ToolError>(()) + }) + .await; + match streamed { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(e), + Err(_) => damage = Some("timed out reading the collector's log".to_string()), } body["files"] = json!(reader.files); body["unread"] = json!(reader.unread); - body["total_bytes"] = json!(reader.files.iter().map(|f| f.bytes).sum::()); + body["total_bytes"] = json!( + reader + .files + .iter() + .map(|f| f.bytes) + .fold(0u64, u64::saturating_add) + ); let failed = |body: &mut Value, error: String| { body["state"] = json!("failed"); body["error"] = json!(error); }; - match (&reader.state, damage) { + let state = reader.state.clone(); + match (state, damage) { (_, Some(error)) => failed(&mut body, error), (State::Withheld(reason), _) => { body["state"] = json!("withheld"); @@ -231,7 +247,15 @@ impl KueueMcp { (State::Archive | State::Complete, _) => { body["state"] = json!("collected"); if let Some(wanted) = wanted { - match reader.unpack() { + let unpacked = tokio::task::spawn_blocking(move || reader.unpack()) + .await + .map_err(|e| { + ToolError::Kube(KubeError::Decode { + what: format!("the results of {name}"), + source: serde_json::Error::io(std::io::Error::other(e.to_string())), + }) + })?; + match unpacked { Err(e) => failed(&mut body, e.to_string()), Ok(files) => { let budget = args