From 991c4af715d439a386a00e794e6ae35a2d4eb546 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Fri, 20 Nov 2026 01:42:06 +0000 Subject: [PATCH] fix: validate stack admit arguments before locking or mutating state run_stack_admit validated the ts option only after it had opened the lock file and moved an existing forecast reservation to waiting, and after any quota or scheduler command had already run. The timestamp helper also reported a malformed value under the generated-at option instead of ts. Direct callers that passed a missing or conflicting quota source likewise opened the lock and rewrote forecast records before failing, and LockKind::parse returned a plain error instead of a usage error. A timestamp_for helper in src/site_commands.rs reports the name of the caller's option, and validate_admit_request runs at the entry of run_stack_admit before the lock is taken or a shell command runs. LockKind::parse failures are wrapped in cli_parse::usage so an invalid lock kind exits with status 2. --- .../+admit-validate-before-mutate.bugfix.md | 1 + src/inode_budget.rs | 34 ++++- src/site_commands.rs | 11 +- tests/admission_forecast_lifecycle.rs | 139 ++++++++++++++++++ 4 files changed, 179 insertions(+), 6 deletions(-) create mode 100644 changelog.d/+admit-validate-before-mutate.bugfix.md diff --git a/changelog.d/+admit-validate-before-mutate.bugfix.md b/changelog.d/+admit-validate-before-mutate.bugfix.md new file mode 100644 index 00000000..761342c5 --- /dev/null +++ b/changelog.d/+admit-validate-before-mutate.bugfix.md @@ -0,0 +1 @@ +`stack admit` validates its timestamp and its quota and live-jobs sources before it takes the lock or runs a command, and reports an invalid timestamp under the ts option instead of generated-at. An invalid lock kind exits with status 2. diff --git a/src/inode_budget.rs b/src/inode_budget.rs index a4f8edee..c2850f17 100644 --- a/src/inode_budget.rs +++ b/src/inode_budget.rs @@ -907,7 +907,9 @@ impl LockKind { match name { "flock" => Ok(Self::Flock), "posix" => Ok(Self::Posix), - other => bail!("lock kind {other:?} is neither flock nor posix"), + other => Err(crate::cli_parse::usage(format!( + "lock kind {other:?} is neither flock nor posix" + ))), } } } @@ -1047,11 +1049,37 @@ fn observe_live_jobs(cmd: &str) -> Result> { Ok(jobs) } +fn validate_admit_request(args: &AdmitRequest) -> Result<()> { + check_job(&args.job).map_err(|error| crate::cli_parse::usage(error.to_string()))?; + match (&args.quota_json, &args.quota_cmd) { + (None, None) => { + return Err(crate::cli_parse::usage( + "--quota-json or --quota-cmd is required", + )); + } + (Some(_), Some(_)) => { + return Err(crate::cli_parse::usage( + "--quota-json and --quota-cmd are mutually exclusive", + )); + } + _ => {} + } + if args.live_jobs.is_some() && args.live_jobs_cmd.is_some() { + return Err(crate::cli_parse::usage( + "--live-jobs and --live-jobs-cmd are mutually exclusive", + )); + } + if let Some(ts) = &args.ts { + crate::site_commands::timestamp_for("--ts", Some(ts.clone()), true)?; + } + Ok(()) +} + /// Under the lock when one is named: observe the quota, read the /// reservations, decide, write the reservation on admit, and remove stale /// reservations only when asked. A failed quota observation refuses. pub fn run_stack_admit(args: &AdmitRequest) -> Result { - check_job(&args.job).map_err(|error| crate::cli_parse::usage(error.to_string()))?; + validate_admit_request(args)?; let _lock = match &args.lock { Some(path) => { let file = std::fs::OpenOptions::new() @@ -1110,7 +1138,7 @@ pub fn run_stack_admit(args: &AdmitRequest) -> Result { } }, }; - let stamp = crate::site_commands::generated_at(args.ts.clone(), true)?; + let stamp = crate::site_commands::timestamp_for("--ts", args.ts.clone(), true)?; let reservations = read_reservations(&args.reservations)?; let mut waiting = BTreeSet::new(); if args.lock.is_some() && refusal.is_none() { diff --git a/src/site_commands.rs b/src/site_commands.rs index afc49a06..551d57ba 100644 --- a/src/site_commands.rs +++ b/src/site_commands.rs @@ -32,8 +32,8 @@ fn rejected_pull_request(flag: &str, number: u64, input: &[u64]) -> String { } } -/// `--generated-at` is stored as given. An absent flag is the current UTC time. -pub(crate) fn generated_at(value: Option, seconds: bool) -> Result { +/// An RFC 3339 timestamp for `flag`, or the current UTC time when absent. +pub(crate) fn timestamp_for(flag: &str, value: Option, seconds: bool) -> Result { let Some(text) = value else { return Ok(if seconds { chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) @@ -42,10 +42,15 @@ pub(crate) fn generated_at(value: Option, seconds: bool) -> Result, seconds: bool) -> Result { + timestamp_for("--generated-at", value, seconds) +} + /// `--version` on `component-reach`: `*`, an exact version, or a requirement. fn require_version_req(version: &str) -> Result<()> { if version == "*" { diff --git a/tests/admission_forecast_lifecycle.rs b/tests/admission_forecast_lifecycle.rs index 480c58e0..bf8ce95b 100644 --- a/tests/admission_forecast_lifecycle.rs +++ b/tests/admission_forecast_lifecycle.rs @@ -274,3 +274,142 @@ fn failed_scheduler_snapshot_preserves_every_reservation_even_with_drop_stale() assert_eq!(fixture.read("12")["phase"], "admitted"); } } + +#[test] +fn invalid_ts_rejects_with_exit_2_before_locking_mutating_or_running_commands() { + let fixture = Fixture::new(); + fixture.record("12", Some("forecast")); + let before = std::fs::read(fixture.reservations.join("12.json")).unwrap(); + let quota_ran = fixture._directory.path().join("quota-ran"); + let live_ran = fixture._directory.path().join("live-ran"); + let quota_cmd = format!( + "touch '{}' && printf '{{\"inodes_available\":500}}'", + quota_ran.display() + ); + let live_cmd = format!("touch '{}' && printf '11,12\\n'", live_ran.display()); + + let output = Command::new(env!("CARGO_BIN_EXE_eb-stack")) + .args(["stack", "admit", "--quota-cmd", "a_cmd]) + .args(["--live-jobs-cmd", &live_cmd]) + .arg("--reservations") + .arg(&fixture.reservations) + .args(["--job", "12", "--footprint", "300", "--margin", "100"]) + .arg("--lock") + .arg(&fixture.lock) + .args(["--lock-kind", "posix", "--ts", "not-a-time"]) + .output() + .unwrap(); + + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(2), "{stderr}"); + assert!( + stderr.contains("--ts not-a-time"), + "expected --ts flag name in stderr: {stderr}" + ); + assert!( + !stderr.contains("--generated-at"), + "unexpected --generated-at in stderr: {stderr}" + ); + assert!( + !fixture.lock.exists(), + "lock file should not be created on rejected usage" + ); + assert_eq!( + std::fs::read(fixture.reservations.join("12.json")).unwrap(), + before, + "forecast record must stay untouched when usage is rejected" + ); + assert!( + !quota_ran.exists(), + "--quota-cmd must not run when usage is rejected" + ); + assert!( + !live_ran.exists(), + "--live-jobs-cmd must not run when usage is rejected" + ); +} + +#[test] +fn invalid_request_sources_reject_before_locking_or_mutating_records() { + let fixture = Fixture::new(); + fixture.record("12", Some("forecast")); + let before = std::fs::read(fixture.reservations.join("12.json")).unwrap(); + + let cases = [ + eb_stack::inode_budget::AdmitRequest { + quota_json: None, + quota_cmd: None, + lock: Some(fixture.lock.clone()), + lock_kind: eb_stack::inode_budget::LockKind::Posix, + unknown_reserve: 0, + drop_stale: false, + footprint: 300, + job: "12".into(), + reservations: fixture.reservations.clone(), + margin: 100, + live_jobs: Some(vec!["12".into()]), + live_jobs_cmd: None, + ts: None, + }, + eb_stack::inode_budget::AdmitRequest { + quota_json: Some(fixture.quota.clone()), + quota_cmd: Some(r#"printf '{"inodes_available":500}'"#.into()), + lock: Some(fixture.lock.clone()), + lock_kind: eb_stack::inode_budget::LockKind::Posix, + unknown_reserve: 0, + drop_stale: false, + footprint: 300, + job: "12".into(), + reservations: fixture.reservations.clone(), + margin: 100, + live_jobs: Some(vec!["12".into()]), + live_jobs_cmd: None, + ts: None, + }, + eb_stack::inode_budget::AdmitRequest { + quota_json: Some(fixture.quota.clone()), + quota_cmd: None, + lock: Some(fixture.lock.clone()), + lock_kind: eb_stack::inode_budget::LockKind::Posix, + unknown_reserve: 0, + drop_stale: false, + footprint: 300, + job: "12".into(), + reservations: fixture.reservations.clone(), + margin: 100, + live_jobs: Some(vec!["12".into()]), + live_jobs_cmd: Some("printf '12\\n'".into()), + ts: None, + }, + ]; + + for request in cases { + let error = eb_stack::inode_budget::run_stack_admit(&request) + .err() + .expect("invalid request should fail"); + assert!( + error + .downcast_ref::() + .is_some(), + "expected usage error, got: {error:#}" + ); + assert!( + !fixture.lock.exists(), + "lock file should not be created on rejected request" + ); + assert_eq!( + std::fs::read(fixture.reservations.join("12.json")).unwrap(), + before, + "forecast record must stay untouched on rejected request" + ); + } + + let bad_kind = eb_stack::inode_budget::LockKind::parse("lockf") + .expect_err("unknown lock kind should fail"); + assert!( + bad_kind + .downcast_ref::() + .is_some(), + "expected usage error from LockKind::parse, got: {bad_kind:#}" + ); +}