Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion crucible-kueue/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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");
}
}
8 changes: 8 additions & 0 deletions crucible-kueue/src/quantity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<S: serde::Serializer>(q: &ParsedQuantity, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&q.to_string())
}
Expand Down
41 changes: 35 additions & 6 deletions crucible-kueue/src/results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,19 @@ struct Found {
bytes: u64,
}

const MAX_DEPTH: usize = 64;

#[derive(Default)]
struct Walk {
files: Vec<Found>,
unread: Vec<Unread>,
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
Expand All @@ -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(),
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)?
Expand All @@ -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)
Expand Down Expand Up @@ -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(_))));
}
}
38 changes: 29 additions & 9 deletions crucible-kueue/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2747,6 +2747,8 @@ impl KueueMcp {
}
}

const MAX_PAGED_LOG_OFFSET: usize = 64 * 1024 * 1024;

impl KueueMcp {
async fn log_page(
&self,
Expand All @@ -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<Pod> = 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),
Expand Down Expand Up @@ -2800,6 +2812,8 @@ fn log_page_request(args: &LogArgs) -> Result<Option<PageRequest>, 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
Expand Down Expand Up @@ -2890,16 +2904,20 @@ async fn follow_log(
until: tokio::time::Instant,
) -> Result<String, kube::Error> {
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<u8> = Vec::new();
let mut kept: VecDeque<u8> = 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);
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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})
Expand Down
62 changes: 43 additions & 19 deletions crucible-kueue/src/server/results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,35 +175,51 @@ impl KueueMcp {
..LogParams::default()
};
let api: Api<Pod> = 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::<u64>());
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");
Expand Down Expand Up @@ -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
Expand Down
Loading