web: fix red-team breaks in restore, drop-open, and plot paths

Three attack agents (state-machine tracing, executable input fuzzing,
browser-API review) found two breaks and several degradations; all are
fixed here, with the fuzzer's 22 tests kept as regression suites.

Breaks:
- Untitled tabs (and dot-names like ".dxf") autosave as DXF, but the
  restore name defaulted to .dwg — the worker dispatches its reader by
  the name's extension, so the only copy of unsaved work could never
  be restored and was re-offered forever. recovered_name now uses the
  worker's rsplit('.') convention and defaults extensionless names to
  dxf, matching new-document serialization.
- " (recovered)" stacked one suffix per crash-restore cycle; the
  marker is now stripped idempotently before appending.
- Opening a file (Ctrl+O / OPEN / automation) while a web open was in
  flight clobbered it: the in-flight open's bytes were lost and every
  queued restore prompt stalled for the session. on_open_file now
  refuses while an open is running (web only).

Hardening:
- Escape on the Recover Drawing modal defers instead of deleting the
  only snapshot; the Discard button still removes it.
- A cap-rejected restore enqueue warns in-app and re-offers the next
  snapshot; the drop queue cap rises to 32.
- Exiting mid-round no longer races snapshot removals (deferrals are
  drained, the sweep skips while a round is in flight); closing a tab
  with "Don't save" now also removes its web snapshot; the snapshot
  key derivation is shared via web_autosave_key.
- The plot-preview overlay no longer leaks a full PDF copy per preview
  (the Download closure lives in a replaceable registry).
- A corrupt autosave index.json fails the round/boot instead of
  silently resetting every row; plot pages with non-finite or non-
  positive sheet dimensions error instead of emitting a NaN MediaBox.
- The drop filter accepts dot-less "DWG"/"dxf" names the worker
  parses (same rsplit convention on both gates).
This commit is contained in:
Afonsop committed 2026-09-16 13:56:08 +01:00
1 parent 64160fd68d
commit 3eab00bfbf
35 files changed
+1356 -76

No files matched your search

+297
View File
@@ -0,0 +1,297 @@
//! RED-TEAM: the Model-branch sheet floor in `layout_plot_page_for`
//! (src/app/update/file.rs:3765-3800, `MIN_MODEL_SHEET_MM = 10.0`) attacked
//! through its REAL input: `Scene::model_space_extents`
//! (src/scene/mod.rs:10925 `compute_model_space_extents`).
//!
//! The App method is `pub(super)` and unconstructible outside the app, so the
//! floor arithmetic is replicated verbatim below and fed the REAL extents of
//! hostile scenes (NaN / ±inf / f64-overflow / reversed-header / huge /
//! exactly-10mm / 9.99mm drawings). The question: can a NaN or non-finite
//! page ever reach `pdf_export`, where `width < MIN` silently compares false
//! for NaN and the "normal" branch would emit a NaN-sized `Mm(paper_w)`?
#![cfg(not(target_arch = "wasm32"))]
use acadrust::entities::Line;
use acadrust::types::Vector3;
use acadrust::EntityType;
use OpenCADStudio::scene::Scene;
fn line(x1: f64, y1: f64, x2: f64, y2: f64) -> EntityType {
let mut l = Line::new();
l.start = Vector3::new(x1, y1, 0.0);
l.end = Vector3::new(x2, y2, 0.0);
EntityType::Line(l)
}
/// Verbatim copy of the Model-branch sheet arithmetic
/// (src/app/update/file.rs:3765-3800), reduced to its inputs:
/// `model_space_extents()` + the dialog sheet (default A4 landscape 297x210).
const MIN_MODEL_SHEET_MM: f64 = 10.0;
fn model_sheet(extents: Option<(f64, f64, f64, f64, f64, f64)>) -> (f64, f64, f64, f64) {
let selected_sheet: (f64, f64) = (297.0, 210.0);
let standard_sheet = {
let (w, h) = selected_sheet;
(w.min(h) >= MIN_MODEL_SHEET_MM).then_some((w, h))
};
if let Some((min_x, min_y, _, max_x, max_y, _)) = extents {
let margin = 1.05_f64;
let width = ((max_x - min_x) as f64 * margin).max(1.0);
let height = ((max_y - min_y) as f64 * margin).max(1.0);
if width < MIN_MODEL_SHEET_MM || height < MIN_MODEL_SHEET_MM {
let (w, h) = standard_sheet.unwrap_or((297.0, 210.0));
let page_w = width.max(w);
let page_h = height.max(h);
(
page_w,
page_h,
(page_w - width) * 0.5 - min_x as f64,
(page_h - height) * 0.5 - min_y as f64,
)
} else {
let pad_x = (width - (max_x - min_x) as f64) * 0.5;
let pad_y = (height - (max_y - min_y) as f64) * 0.5;
(width, height, -(min_x as f64) + pad_x, -(min_y as f64) + pad_y)
}
} else {
(297.0, 210.0, 0.0, 0.0)
}
}
fn flat_extents(scene: &Scene) -> Option<(f64, f64, f64, f64, f64, f64)> {
scene
.model_space_extents()
.map(|(min, max)| (min.x as f64, min.y as f64, min.z as f64, max.x as f64, max.y as f64, max.z as f64))
}
/// Entities with NaN coordinates must not poison the sheet: the extents pass
/// in `compute_model_space_extents` drops non-finite vertices
/// (src/scene/mod.rs:10945 `(x as f32).is_finite()`), so NaN alone yields
/// `None` (default 297x210 page) and NaN mixed with real geometry yields the
/// finite bounds only. The `width < MIN` NaN trap in the floor branch is
/// unreachable through this input.
#[test]
fn nan_entities_cannot_produce_a_nan_or_floored_wrongly_page() {
// Only-NaN drawing: no usable extents at all.
let mut scene = Scene::new();
scene.add_entity(line(f64::NAN, f64::NAN, f64::NAN, f64::NAN));
scene.add_entity(line(0.0, f64::NAN, 10.0, f64::NAN));
let extents = flat_extents(&scene);
assert!(
extents.is_none(),
"NaN-only geometry must yield None, got {extents:?}"
);
let (w, h, ox, oy) = model_sheet(extents);
assert_eq!((w, h), (297.0, 210.0));
assert_eq!((ox, oy), (0.0, 0.0));
// NaN contaminating an otherwise finite drawing.
let mut scene = Scene::new();
scene.add_entity(line(0.0, 0.0, 10.0, 10.0));
scene.add_entity(line(f64::NAN, 5.0, f64::NAN, 5.0));
let (w, h, ox, oy) = model_sheet(flat_extents(&scene));
assert_eq!((w, h), (10.5, 10.5), "10mm * 1.05 margin, NaN entity ignored");
assert!(w.is_finite() && h.is_finite() && ox.is_finite() && oy.is_finite());
// Every scene fed to the floor keeps the invariant the branch promises:
// a real, finite page of at least MIN on both axes.
let mut hostile = vec![
Scene::new(), // empty drawing
];
let mut inf_scene = Scene::new();
inf_scene.add_entity(line(f64::NEG_INFINITY, 0.0, f64::INFINITY, f64::INFINITY));
hostile.push(inf_scene);
let mut overflow_scene = Scene::new(); // finite f64, overflows f32
overflow_scene.add_entity(line(-1e300, -1e300, 1e300, 1e300));
hostile.push(overflow_scene);
let mut huge_f32_scene = Scene::new(); // finite even after the f32 cast
huge_f32_scene.add_entity(line(-3.0e38, -3.0e38, 3.0e38, 3.0e38));
hostile.push(huge_f32_scene);
for scene in &hostile {
let extents = flat_extents(scene);
if let Some((mnx, mny, _, mxx, mxy, _)) = extents {
assert!(
mnx.is_finite() && mny.is_finite() && mxx.is_finite() && mxy.is_finite(),
"extents must be finite: {extents:?}"
);
assert!(mnx <= mxx && mny <= mxy, "min/max must be ordered: {extents:?}");
}
let (w, h, ox, oy) = model_sheet(extents);
assert!(w.is_finite() && h.is_finite() && ox.is_finite() && oy.is_finite());
assert!(w >= MIN_MODEL_SHEET_MM && h >= MIN_MODEL_SHEET_MM, "({w}, {h})");
}
}
/// A drawing whose only coordinates exceed f32 range (e.g. 1e300) is silently
/// dropped from the extents (the `(x as f32).is_finite()` filter) — the plot
/// falls back to the default sheet, so the drawing PLOTS EMPTY rather than
/// erroring. Behavior note, not a crash.
#[test]
fn beyond_f32_range_geometry_is_silently_ignored_by_extents() {
let mut scene = Scene::new();
scene.add_entity(line(1e300, 1e300, 2e300, 2e300));
assert!(
flat_extents(&scene).is_none(),
"1e300 coordinates overflow the f32 wire cache and vanish from extents"
);
// While geometry at f32::MAX-ish scale stays (absurd page, but finite).
let mut scene = Scene::new();
scene.add_entity(line(-3.0e38, 0.0, 3.0e38, 3.0e38));
let (w, h, _, _) = model_sheet(flat_extents(&scene));
assert!(w > 1.0e38 && h > 1.0e38, "({w}, {h})");
}
/// The reversed-extents case (min > max) cannot come from
/// `compute_model_space_extents` (min starts at +inf and only decreases) and
/// the EXTMIN/EXTMAX header fallback rejects it with a strict `<`
/// (src/scene/mod.rs:11005). A fresh document's header is reversed by
/// DEFAULT (1e20 / -1e20 sentinels) and its model-space block record exists,
/// so an empty drawing exercises the header path immediately.
#[test]
fn reversed_extents_are_unreachable_even_from_a_hostile_header() {
// Real parsed document (has a *Model_Space block), all entities removed:
// the header fallback is the only extents source left. One fresh scene
// per case — `model_space_extents` caches by geometry_epoch, and header
// mutation alone does not bump the epoch.
let empty_scene = || {
let mut scene = Scene::new();
scene.document = OpenCADStudio::io::load_bytes(
"embedded-image-print.dxf",
include_bytes!("fixtures/embedded-image-print.dxf").to_vec(),
)
.expect("fixture");
let handles: Vec<_> = scene.document.entities().map(|e| e.common().handle).collect();
for handle in handles {
scene.document.remove_entity(handle);
}
scene
};
// Reversed header: rejected.
let mut scene = empty_scene();
scene.document.header.model_space_extents_min = Vector3::new(100.0, 100.0, 0.0);
scene.document.header.model_space_extents_max = Vector3::new(-100.0, -100.0, 0.0);
assert!(
flat_extents(&scene).is_none(),
"reversed EXTMIN/EXTMAX must be rejected, not negated into a page"
);
// NaN header: also rejected by the strict `<` (NaN comparisons are false).
let mut scene = empty_scene();
scene.document.header.model_space_extents_min = Vector3::new(f64::NAN, f64::NAN, 0.0);
scene.document.header.model_space_extents_max = Vector3::new(10.0, 10.0, 0.0);
assert!(flat_extents(&scene).is_none(), "NaN EXTMIN must be rejected");
// Ordered, sane header alone (no drawable geometry) feeds the plot
// through the fallback path.
let mut scene = empty_scene();
scene.document.header.model_space_extents_min = Vector3::new(-100.0, -100.0, 0.0);
scene.document.header.model_space_extents_max = Vector3::new(100.0, 100.0, 0.0);
let extents = flat_extents(&scene)
.expect("ordered sane header feeds the fallback");
assert_eq!((extents.0, extents.1, extents.3, extents.4), (-100.0, -100.0, 100.0, 100.0));
let (w, h, ox, oy) = model_sheet(Some(extents));
// 200mm extents * 1.05 = 210mm page (normal branch, above the floor);
// offset = -min + (210 - 200)/2 margin padding = 100 + 5.
assert_eq!((w, h), (210.0, 210.0));
assert!((ox - 105.0).abs() < 1e-9 && (oy - 105.0).abs() < 1e-9);
}
/// The floor boundary: the floor compares the MARGIN-INCLUDED size
/// (`extents * 1.05`), not the raw extents, so "exactly 10.0mm" and even
/// 9.99mm drawings take the NORMAL branch (page = 10.5mm and 10.4895mm
/// respectively) — the floor only catches extents below 10/1.05 ≈ 9.524mm.
/// A 9.5mm x 10000mm profile IS floored, per-axis: 297mm wide, 10500mm tall,
/// with the content centered by the offsets.
#[test]
fn floor_boundary_math_per_axis() {
// Exactly 10.0mm extents: normal branch (10 * 1.05 = 10.5 >= 10).
let (w, h, _, _) = model_sheet(Some((0.0, 0.0, 0.0, 10.0, 10.0, 0.0)));
assert_eq!((w, h), (10.5, 10.5));
// 9.99 x 10000: STILL the normal branch (9.99 * 1.05 = 10.4895 >= 10) —
// the task's guess "(297, 10000+5%)" is off by the margin.
let (w, h, _, _) = model_sheet(Some((0.0, 0.0, 0.0, 9.99, 10000.0, 0.0)));
assert!((w - 10.4895).abs() < 1e-9);
assert!((h - 10500.0).abs() < 1e-9);
// 9.5 x 10000: floored per-axis — thin axis lifted to the standard sheet
// width (297), long axis keeps its margin size, content centered.
let (w, h, ox, oy) = model_sheet(Some((0.0, 0.0, 0.0, 9.5, 10000.0, 0.0)));
assert_eq!(w, 297.0);
assert!((h - 10500.0).abs() < 1e-9);
// width = 9.5 * 1.05 = 9.975 → offset_x = (297 - 9.975)/2 - 0 = 143.5125
assert!((ox - (297.0 - 9.975) * 0.5).abs() < 1e-9);
// height = 10500 exactly fills the page → offset_y = -min_y = 0.
assert!((oy - 0.0).abs() < 1e-9);
// A dot (zero extents): width clamped to 1.0 by `.max(1.0)`, floored to
// the full standard sheet, offsets center the dot's point.
let (w, h, ox, oy) = model_sheet(Some((5.0, 7.0, 0.0, 5.0, 7.0, 0.0)));
assert_eq!((w, h), (297.0, 210.0));
assert!((ox - ((297.0 - 1.0) * 0.5 - 5.0)).abs() < 1e-9);
assert!((oy - ((210.0 - 1.0) * 0.5 - 7.0)).abs() < 1e-9);
}
/// Defense-in-depth check at the pdf_export layer: if a NaN page size ever
/// DID reach it (future regression, or a non-Model branch), what happens?
/// `PdfPageInput.paper_w = NaN` used to be serialized verbatim into a
/// MediaBox containing the literal string "nan" — a nominally-valid PDF no
/// conforming viewer can display (and which printpdf's own parser even
/// accepts). The paper fields are now validated like the content
/// coordinates (src/io/pdf_export.rs `append_pdf_page`): non-finite or
/// non-positive dimensions are rejected with a plain-English error.
#[test]
fn pdf_export_layer_faced_with_a_nan_page_size() {
use OpenCADStudio::io::pdf_export::{export_pdf, PdfPageInput, PdfPlotOptions};
let path = std::env::temp_dir().join(format!(
"ocs-redteam-nan-page-{}.pdf",
std::process::id()
));
for (paper_w, paper_h) in [
(f64::NAN, f64::NAN),
(f64::NAN, 297.0),
(210.0, f64::INFINITY),
(f64::NEG_INFINITY, 297.0),
(0.0, 297.0),
(210.0, 0.0),
(-210.0, 297.0),
] {
let page = PdfPageInput {
content: Default::default(),
paper_w,
paper_h,
offset_x: 0.0,
offset_y: 0.0,
rotation_deg: 0,
scale: 1.0,
clip: None,
options: PdfPlotOptions::default(),
plot_style: None,
};
let error = export_pdf(&page, &path)
.expect_err("non-finite/zero sheet sizes must be rejected, not plotted");
assert!(
error.contains("plot sheet size is not valid"),
"page ({paper_w}, {paper_h}): {error}"
);
assert!(
!path.exists(),
"no artifact may be written for a rejected sheet"
);
}
// A sane sheet still exports normally.
let page = PdfPageInput {
content: Default::default(),
paper_w: 210.0,
paper_h: 297.0,
offset_x: 0.0,
offset_y: 0.0,
rotation_deg: 0,
scale: 1.0,
clip: None,
options: PdfPlotOptions::default(),
plot_style: None,
};
export_pdf(&page, &path).expect("sane sheet exports");
assert!(path.exists());
let bytes = std::fs::read(&path).unwrap();
assert!(
!String::from_utf8_lossy(&bytes).to_lowercase().contains("nan"),
"no NaN may leak into a written page"
);
let _ = std::fs::remove_file(&path);
}
+166
View File
@@ -0,0 +1,166 @@
//! RED-TEAM: the web drag&drop name filter (`src/io/web_drop.rs`
//! `is_drawing_name`) cross-checked against the parse-worker extension gate
//! (`crates/ocs_web_worker/src/lib.rs:44-52`) it is supposed to pre-empt.
//!
//! A drop that passes the filter but fails the worker is a user-visible dead
//! end (file read, queued, then a parse error); a drop that fails the filter
//! for bytes the worker COULD parse is a silently ignored file. The two gates
//! are one-liners (`pub(crate)`/inline, invisible to integration tests), so
//! they are replicated VERBATIM here and fuzzed against each other; verdicts
//! are cross-checked with the real native loader `OpenCADStudio::io::load_bytes`
//! (src/io/mod.rs:722), which derives the format from the name exactly like
//! the worker.
#![cfg(not(target_arch = "wasm32"))]
const FIXTURE_DXF: &[u8] = include_bytes!("fixtures/embedded-image-print.dxf");
/// Verbatim copy of src/io/web_drop.rs (is_drawing_name).
fn is_drawing_name(name: &str) -> bool {
matches!(
name.rsplit('.').next().unwrap_or_default().to_ascii_lowercase().as_str(),
"dwg" | "dxf"
)
}
/// Verbatim copy of the worker's gate (crates/ocs_web_worker/src/lib.rs:44-52).
fn worker_accepts(name: &str) -> bool {
let ext = name.rsplit('.').next().unwrap_or_default().to_lowercase();
matches!(ext.as_str(), "dwg" | "dxf")
}
/// REGRESSION (fixed): the drop filter and the worker gate now share the
/// `rsplit('.').next()` convention, so a file literally named "DWG"/"dxf"
/// (no dot) is accepted by BOTH — previously the filter silently ignored
/// files the parser behind it would have opened.
#[test]
fn extensionless_dwg_named_files_are_dropped_but_parseable() {
for name in ["DWG", "dwg", "Dwg", "DXF", "dxf"] {
assert!(
is_drawing_name(name),
"{name:?}: drop filter accepts (worker convention)"
);
assert!(worker_accepts(name), "{name:?}: worker gate accepts");
// The native loader shares the worker's convention: same bytes+name
// it would reach the DXF/DWG reader (fixture is DXF, so the dxf
// spellings truly parse; dwg spellings reach the DWG reader).
let result = OpenCADStudio::io::load_bytes(name, FIXTURE_DXF.to_vec());
assert_eq!(
result.is_ok(),
name.to_ascii_lowercase() == "dxf",
"{name:?}: format is picked from the dot-less name itself"
);
}
}
/// For every name CONTAINING a dot the two gates agree: no dead end (filter
/// pass + worker refuse) and no silently ignored parseable file (filter
/// refuse + worker accept). Attacked with the hostile matrix.
#[test]
fn drop_filter_and_worker_gate_agree_on_dotted_names() {
let hostile = [
"plan.dwg", // baseline
".DWG", // uppercase dot-file: accepted by BOTH
".dwg", // dot-file
"x.dwg ", // trailing space (legal on Linux)
"x.dwg\u{a0}", // trailing non-breaking space
"x .dwg", // space before extension
"x.dwgx", // near-miss extension
"x.dwg.tar", // double extension
"x.DwF", // Design Web Format: rejected
"x.DXF", // uppercase: accepted
"x.dxf.", // trailing dot: rejected
".", // only a dot
"..", // only dots
"…", // only an ellipsis char (not a dot)
"", // empty (no dot — covered by the other test)
"x.dωg", // Greek omega lookalike
"x.dWg", // fullwidth W (U+FF37)
"x.dwg\n", // trailing newline
"\nx.dwg", // leading newline
"x.d\u{0130}f", // dotted capital I (full lowercase => 2 chars)
"x.dx\u{212a}", // KELVIN SIGN lowercases to 'k'
"con.dwg", // Windows reserved stem
"a.b.dxf", // multi-dot
"plán.dwg", // unicode stem
"図面.dxf", // CJK stem
"plan.sv$", // native autosave copy: rejected on web
"plan.bak", // native backup: rejected on web
];
for name in hostile {
assert_eq!(
is_drawing_name(name),
worker_accepts(name),
"drop filter and worker gate disagree on {name:?}"
);
}
// Spot-check the interesting verdicts against the REAL loader (the
// native `load_bytes` shares the rsplit('.') convention).
assert!(is_drawing_name(".DWG") && worker_accepts(".DWG"));
assert!(
OpenCADStudio::io::load_bytes(".DWG", FIXTURE_DXF.to_vec()).is_err(),
"dot-file '.DWG' is gated IN by both, then parsed as DWG (bytes decide)"
);
assert!(!is_drawing_name("x.dwg ") && !worker_accepts("x.dwg "));
let err = OpenCADStudio::io::load_bytes("x.dwg ", FIXTURE_DXF.to_vec()).unwrap_err();
assert!(err.contains("Unsupported file format"), "{err}");
// No unicode fold can turn a non-ASCII extension into "dwg"/"dxf":
// the only single-char case-folds onto ASCII letters are ASCII
// themselves (plus KELVIN SIGN -> k, not in the set), so ascii-vs-full
// lowercase cannot diverge for these two literals.
assert!(!is_drawing_name("x.dx\u{212a}"));
assert!(!worker_accepts("x.dx\u{212a}"));
}
/// Web/native divergence, real-code proof: `.sv$` and `.bak` files open
/// NATIVELY (sniffed, src/io/mod.rs:723) but are refused by BOTH web gates —
/// a user switching a crash-recovered `.sv$` from desktop to web gets a
/// console warning and nothing else.
#[test]
fn sv_dollar_and_bak_open_natively_but_are_refused_on_web() {
assert!(!is_drawing_name("plan.sv$"));
assert!(!worker_accepts("plan.sv$"));
assert!(!is_drawing_name("plan.bak"));
assert!(!worker_accepts("plan.bak"));
// The native loader sniffs the same bytes under the same name.
assert!(OpenCADStudio::io::load_bytes("plan.sv$", FIXTURE_DXF.to_vec()).is_ok());
assert!(OpenCADStudio::io::load_bytes("plan.bak", FIXTURE_DXF.to_vec()).is_ok());
// ...and refuses the web-refused near-misses identically.
assert!(OpenCADStudio::io::load_bytes("plan.dwgx", FIXTURE_DXF.to_vec()).is_err());
}
/// The filter is name-only: a `.dwg`-named file whose bytes are DXF passes
/// both gates and dies in the DWG reader — the dead end the filter cannot
/// prevent (and cannot be expected to).
#[test]
fn filter_cannot_catch_bytes_format_mismatch() {
assert!(is_drawing_name("actually-dxf.dwg"));
assert!(worker_accepts("actually-dxf.dwg"));
let error = OpenCADStudio::io::load_bytes("actually-dxf.dwg", FIXTURE_DXF.to_vec())
.expect_err("DWG reader rejects DXF bytes");
assert!(!error.contains("Unsupported file format"), "{error}");
}
/// Fuzz: over every short ASCII name, the ONLY divergences are the dot-less
/// exact "dwg"/"dxf" spellings pinned above — no other mismatch exists.
#[test]
fn exhaustive_short_name_agreement_except_extensionless_spelling() {
let alphabet: Vec<u8> = (b'.'..=b'z').collect();
let mut buffer = [0u8; 3];
for &a in &alphabet {
for &b in &alphabet {
for &c in &alphabet {
buffer = [a, b, c];
let name = std::str::from_utf8(&buffer).unwrap();
let filter = is_drawing_name(name);
let worker = worker_accepts(name);
if filter != worker {
// The one known class: dot-less exact spelling.
assert!(
!name.contains('.') && worker,
"unexpected divergence on {name:?}"
);
}
}
}
}
}
+95
View File
@@ -0,0 +1,95 @@
//! RED-TEAM: the web export filename pipeline
//! `pick_stl_path_owned`/`pick_step_path_owned` (src/io/stl.rs:102-104,
//! src/io/step.rs:258-260, wasm-only one-liners) fed by
//! `tab.current_path.file_stem()` (src/app/update/mod.rs:1310-1315) and
//! consumed by `sys::download_bytes` via `path.file_name()`
//! (src/app/update/file.rs:1717-1721, src/sys.rs:348-372).
//!
//! The wasm functions are cfg'd out on native, so the exact composition is
//! replicated here (it is pure `Path` semantics + `format!`) and attacked
//! with hostile current_paths. `download_bytes` itself only ever passes the
//! string to `a.set_download` — a plain JS property set that cannot panic in
//! Rust; browsers sanitize separators/control characters in the attribute.
#![cfg(not(target_arch = "wasm32"))]
/// Verbatim composition of the web flow: stem extraction (mod.rs:1310-1315)
/// -> virtual path (stl.rs:103 / step.rs:259) -> download name
/// (file.rs:1717-1721).
fn stl_download_name(current_path: Option<&std::path::Path>) -> String {
let stem = current_path
.and_then(|p| p.file_stem())
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "drawing".into());
let path = std::path::PathBuf::from(format!("{stem}.stl"));
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "export.stl".into())
}
fn step_download_name(current_path: Option<&std::path::Path>) -> String {
let stem = current_path
.and_then(|p| p.file_stem())
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| "drawing".into());
let path = std::path::PathBuf::from(format!("{stem}.step"));
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "export.step".into())
}
/// Path separators coming from a hostile display name never survive into the
/// download: `file_stem()` already drops the directory part, and the
/// re-parsed virtual path's `file_name()` drops it again. No matter what
/// "current_path" a host page injects (the JS entry `ocs_web_drop_file`
/// accepts arbitrary name strings), the download filename cannot traverse.
#[test]
fn separators_and_dotdots_never_reach_the_download_name() {
// Host page drops "a/b.dwg" — name with a forward separator.
let name = stl_download_name(Some(std::path::Path::new("a/b.dwg")));
assert_eq!(name, "b.stl");
// Windows-style separator (web targets unix path rules: not a separator
// there, but `file_name()` strips any leading "./" etc.; backslashes
// survive as literal characters — browsers strip them in the download
// attribute, and they cannot traverse OPFS because the name is never
// used as a path, only as a display string + FNV-hash key input).
let name = stl_download_name(Some(std::path::Path::new("..\\evil.dwg")));
#[cfg(windows)]
assert_eq!(name, "evil.stl");
#[cfg(not(windows))]
assert_eq!(name, "..\\evil.stl");
// Pure ".." cannot be a stem: file_stem() of ".." is None -> "drawing".
assert_eq!(stl_download_name(Some(std::path::Path::new(".."))), "drawing.stl");
assert_eq!(step_download_name(Some(std::path::Path::new(".."))), "drawing.step");
// No path at all (untitled tab).
assert_eq!(stl_download_name(None), "drawing.stl");
assert_eq!(step_download_name(None), "drawing.step");
// Extension-less drawing name.
assert_eq!(stl_download_name(Some(std::path::Path::new("Drawing1"))), "Drawing1.stl");
}
/// Quotes, newlines, control characters and unicode ride through as inert
/// string bytes: the Rust side does no filesystem or shell operation with
/// them (`download_bytes` builds a Blob and sets the `download` attribute —
/// src/sys.rs:356-369 — which cannot panic). NOTE: even an interior NUL
/// survives the whole Rust pipeline (std::path only rejects it at OS
/// boundaries, and there are none on web) — JS strings legally contain NUL,
/// and the browser sanitizes it in the download attribute. No injection, no
/// panic — verified by construction of the pipeline.
#[test]
fn quote_and_control_char_stems_stay_inert_strings() {
for hostile in [
"ev\"il", "ev'il", "line\nbreak", "tab\there", "cr\r lf", "nul\u{0}ish",
"café", "図面", "..\\..\\evil", "con", "..",
] {
let path = std::path::PathBuf::from(format!("{hostile}.dwg"));
let name = stl_download_name(Some(&path));
assert!(name.ends_with(".stl"), "{name:?}");
let step_name = step_download_name(Some(&path));
assert!(step_name.ends_with(".step"), "{step_name:?}");
}
// Pin the surprising-but-harmless case: an interior NUL is NOT stripped
// anywhere in Rust; it would reach `set_download` as a JS string
// containing U+0000 (legal), and the browser scrubs it.
let name = stl_download_name(Some(std::path::Path::new("nul\u{0}ish.dwg")));
assert_eq!(name, "nul\u{0}ish.stl");
}
+134
View File
@@ -0,0 +1,134 @@
//! RED-TEAM: the FNV-1a name-hash keying shared by `web_recent` and
//! `web_autosave` (`src/io/web_recent.rs:225-242`, `pub(crate)` — replicated
//! verbatim below; OPFS itself is browser-only).
//!
//! Questions attacked:
//! 1. Does the code rely on hash uniqueness? (Reading: YES — a collision
//! silently merges two drawings' OPFS entries; see test docs below.)
//! 2. Unicode normalization: NFC vs NFD "café.dwg" hash differently.
//! 3. Are real collisions findable? (Pollard-rho result pinned below.)
#![cfg(not(target_arch = "wasm32"))]
/// Verbatim copy of src/io/web_recent.rs:235-242.
fn name_hash(name: &str) -> String {
let mut hash = 0xcbf29ce484222325_u64;
for byte in name.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
format!("{hash:016x}")
}
/// Verbatim composition of the OPFS entry names both stores derive from it
/// (web_recent.rs:225-231, web_autosave.rs:205-211).
fn cache_key(name: &str) -> String {
format!("{}.cad", name_hash(name))
}
fn thumbnail_key(name: &str) -> String {
format!("{}.thumb", name_hash(name))
}
fn snapshot_key(name: &str) -> String {
format!("{}.sv$", name_hash(name))
}
/// The implementation is exactly canonical FNV-1a 64 (offset basis, then
/// xor-byte/multiply per byte) — pinned against the reference vectors so the
/// collision analysis below applies to the shipped code.
#[test]
fn the_hash_is_canonical_fnv1a_64() {
assert_eq!(name_hash(""), format!("{:016x}", 0xcbf29ce484222325_u64));
assert_eq!(name_hash("a"), format!("{:016x}", 0xaf63dc4c8601ec8c_u64));
assert_eq!(name_hash("foobar"), format!("{:016x}", 0x85944171f73967e8_u64));
// Keys are bare hex + fixed suffixes: they can never contain path
// separators or grow with the drawing name, whatever the name contains.
for hostile in [
"../evil.dwg",
"..\\evil.dxf",
"a/b/c.dwg",
"nul\u{0}.dwg",
"plan.sv$",
"",
"x".repeat(4096).as_str(),
] {
let key = snapshot_key(hostile);
let (prefix, suffix) = key.split_at(16);
assert!(prefix.chars().all(|c| c.is_ascii_hexdigit()), "{key:?}");
assert_eq!(suffix, ".sv$");
assert_eq!(cache_key(hostile).len(), ".cad".len() + 16);
assert_eq!(thumbnail_key(hostile).len(), ".thumb".len() + 16);
}
}
/// Unicode normalization: "café.dwg" in NFC (single U+00E9) and NFD
/// ("e" + U+0301) are the SAME visual name but different byte strings, so
/// they get different keys — two recents entries, two autosave snapshots,
/// two tabs that look identical to the user. Harm has two edges:
/// - mostly benign: each entry stores/loads its own bytes consistently;
/// - confusing: a user with an NFD-named file on disk and an NFC-named copy
/// from the web picker sees the "same" drawing twice in the Start page and
/// the pair never share an autosave snapshot, so recovering one does not
/// recover the other. Not corruption — a duplicate-entry wart.
#[test]
fn nfc_and_nfd_names_hash_to_distinct_entries() {
let nfc = "caf\u{e9}.dwg"; // U+00E9
let nfd = "cafe\u{301}.dwg"; // e + combining acute
assert_eq!(nfc, nfd.nfc_str()); // visually/normalization-wise the "same" name
assert_ne!(nfc.as_bytes(), nfd.as_bytes());
assert_ne!(name_hash(nfc), name_hash(nfd));
assert_ne!(snapshot_key(nfc), snapshot_key(nfd));
assert_ne!(cache_key(nfc), cache_key(nfd));
}
trait Nfc {
fn nfc_str(&self) -> String;
}
impl Nfc for str {
fn nfc_str(&self) -> String {
// Minimal NFC for the one case under test: precomposed é.
self.replace("e\u{301}", "\u{e9}")
}
}
/// REAL COLLISION (Pollard-rho, ~1.1e9 steps / 208 s in a release build over
/// 10-char printable names): two different drawing FILE NAMES that share one
/// FNV-1a 64 hash — and therefore ONE OPFS entry in BOTH stores. Found on
/// the 10-char stems; because FNV processes bytes sequentially and the two
/// stems reach the SAME intermediate state, appending the same ".dwg" suffix
/// preserves the collision, so these are full realistic filenames.
///
/// The code has no defense: `web_recent::store` writes `cache_key(name)`
/// blindly (web_recent.rs:34) and `web_autosave::snapshot` writes
/// `snapshot_key(name)` blindly (web_autosave.rs:116), each keyed ONLY by
/// the hash. With these two names in play:
/// * the recents copy of the first drawing is OVERWRITTEN by the second
/// (the Start page then reopens the second's bytes under the first's
/// name — and, if the extensions differ, parses them with the WRONG
/// reader: ".dxf" name + DWG bytes);
/// * the autosave index (web_autosave.rs:112-115) keeps BOTH names, but
/// both rows resolve to the same snapshot file — restoring "the first"
/// silently hands back the second drawing's geometry, and deleting one
/// after its restore (web_autosave.rs:137-151 `remove`) kills the
/// other's snapshot too (the dead row is filtered on the next scan).
/// Probability for organically-chosen names is birthday-bound (~2^-64 per
/// pair, ~2^-13 even for a 100-drawing pool), so this is theoretical for
/// real users — but it is a total, silent loss of the uniqueness
/// assumption. Storing the name alongside the bytes and verifying payload
/// identity on read (the index already maps hash->name), or keying on a
/// longer digest (SHA-256/BLAKE3 truncated to 32 hex chars), would close it.
#[test]
fn two_different_names_share_one_key() {
let (a, b) = (COLLISION_A, COLLISION_B);
assert_ne!(a, b, "collision pair must be distinct names");
assert!(a.is_ascii() && b.is_ascii());
assert!(a.ends_with(".dwg") && b.ends_with(".dwg"));
assert_eq!(name_hash(a), name_hash(b), "pinned collision must hold");
assert_eq!(snapshot_key(a), snapshot_key(b));
assert_eq!(cache_key(a), cache_key(b));
assert_eq!(thumbnail_key(a), thumbnail_key(b));
}
// Pollard-rho result (verify_coll / find_b reconstructions, byte-exact):
// stems `"GK@"Qo8if` [22 47 4b 40 22 51 6f 38 69 66] and `%e+k]u[/],`
// [25 65 2b 6b 5d 75 5b 2f 5d 2c] both hash to a95b939b46c157f8.
const COLLISION_A: &str = "\"GK@\"Qo8if.dwg";
const COLLISION_B: &str = "%e+k]u[/],.dwg";
+344
View File
@@ -0,0 +1,344 @@
//! RED-TEAM: hostile inputs against the web autosave restore-name pipeline
//! (`src/io/web_autosave.rs` `recovered_name` / `newer_than_saved` /
//! `cap_evictions`) and the parse-worker extension gate it must satisfy
//! (`crates/ocs_web_worker/src/lib.rs`).
//!
//! `recovered_name` & co. are `pub(crate)` and OPFS is browser-only, so the
//! three pure helpers are copied VERBATIM below (marked) and their behaviour
//! pinned here; every claim that can be exercised through real shipped code
//! (`OpenCADStudio::io::load_bytes`, which derives the format from the name
//! exactly like the worker: `name.rsplit('.').next()`, src/io/mod.rs:722)
//! is tested against the real code.
#![cfg(not(target_arch = "wasm32"))]
const FIXTURE_DXF: &[u8] = include_bytes!("fixtures/embedded-image-print.dxf");
// ── Verbatim copies (pub(crate), invisible to integration tests) ───────────
/// Verbatim copy of src/io/web_autosave.rs `recovered_name` (incl. the
/// `RECOVERED_MARKER` const, inlined).
const RECOVERED_MARKER: &str = " (recovered)";
fn recovered_name(drawing: &str) -> String {
let (head, ext) = match drawing.rsplit_once('.') {
Some((head, ext)) if !ext.is_empty() => (head, ext.to_string()),
// No dot (or a trailing one): the whole name is the stem.
_ => (drawing, "dxf".to_string()),
};
// A hostile stored name must not smuggle path separators into the tab
// title / download name: keep only the final component of the head.
let head = head.rsplit(['/', '\\']).next().unwrap_or_default();
// When the split consumed everything (".dxf") fall back to the whole
// stored name, like `Path::file_stem`'s empty-stem fallback did.
let mut stem = if head.is_empty() {
drawing
} else {
head
};
// Idempotent: strip every trailing marker, then append exactly one.
while let Some(stripped) = stem.strip_suffix(RECOVERED_MARKER) {
stem = stripped;
}
format!("{stem}{RECOVERED_MARKER}.{ext}")
}
/// Verbatim copy of src/io/web_autosave.rs:52-57.
fn newer_than_saved(autosave_ms: f64, saved_ms: Option<f64>) -> bool {
match saved_ms {
Some(saved_ms) => autosave_ms > saved_ms,
None => true,
}
}
/// Verbatim copy of src/io/web_autosave.rs:39-43 + 71-84.
#[derive(Debug, Clone)]
struct WebAutosaveEntry {
name: String,
size: u64,
modified_ms: f64,
}
const SNAPSHOT_CAP: usize = 16;
fn cap_evictions(
mut entries: Vec<WebAutosaveEntry>,
cap: usize,
) -> (Vec<WebAutosaveEntry>, Vec<String>) {
entries.sort_by(|a, b| b.modified_ms.total_cmp(&a.modified_ms));
let overflow = entries.len().saturating_sub(cap);
let mut evicted: Vec<String> = entries
.split_off(entries.len() - overflow)
.into_iter()
.map(|entry| entry.name)
.collect();
evicted.reverse();
(entries, evicted)
}
/// Verbatim copy of the worker's extension gate
/// (crates/ocs_web_worker/src/lib.rs:44-52): the restore name must pass this
/// or the drawing can NEVER be reopened — a restore that always fails is a
/// data-loss trap (the snapshot is only deleted on a successful open).
fn worker_accepts(name: &str) -> bool {
let ext = name.rsplit('.').next().unwrap_or_default().to_lowercase();
matches!(ext.as_str(), "dwg" | "dxf")
}
fn entry(name: &str, modified_ms: f64) -> WebAutosaveEntry {
WebAutosaveEntry {
name: name.to_string(),
size: 16,
modified_ms,
}
}
/// Every recovered name must keep an extension the parse worker accepts —
/// otherwise the offered snapshot can never be restored, only discarded.
#[test]
fn recovered_names_that_the_parse_worker_refuses() {
// The extension is preserved verbatim: a ".sv$" name restores as ".sv$",
// which the web worker rejects ("Unsupported file format: .sv$",
// crates/ocs_web_worker/src/lib.rs:45) — while the NATIVE loader sniffs
// the real format for sv$/bak (src/io/mod.rs:723) and opens it anyway.
for input in ["plan.sv$", "plan.bak", "plan.dwf", "plan.dwgx", "pl.an"] {
let output = recovered_name(input);
assert!(
!worker_accepts(&output),
"recovered_name({input:?}) = {output:?} is refused by the parse worker"
);
}
// Real-code proof of the web/native divergence: native `load_bytes`
// derives the format from the name exactly like the worker, BUT sniffs
// sv$/bak — the same bytes+name the worker refuses open natively.
assert!(
OpenCADStudio::io::load_bytes("plan (recovered).sv$", FIXTURE_DXF.to_vec()).is_ok(),
"native loader sniffs sv$ and opens; only the web worker refuses"
);
// Non-sniffed unknown extensions are refused by BOTH loaders (the
// replica gate mirrors the worker; load_bytes is the real thing).
let err = OpenCADStudio::io::load_bytes("plan (recovered).dwf", FIXTURE_DXF.to_vec())
.expect_err("real loader must refuse .dwf");
assert!(err.contains("Unsupported file format"), "{err}");
}
/// FIXED (was BREAK, verified by reading + real-loader proof): a drawing
/// whose FILE NAME is exactly ".dxf" (a dot-file — accepted by BOTH the drop
/// filter and the worker, which split on the last dot) is serialized by
/// autosave as DXF (`source_is_dxf` falls through to
/// `dwg_source_version.is_none()` because `Path::extension(".dxf")` is
/// None). The old `Path::extension`-based `recovered_name` restored it as
/// ".dwg" — feeding DXF bytes to the DWG reader, so the restore could never
/// succeed and the snapshot was re-offered at every boot (it is deleted only
/// on a successful open). The extension split now follows the WORKER
/// convention (`name.rsplit('.').next()`), so ".dxf" restores as ".dxf".
#[test]
fn dotfile_dxf_restores_as_dxf_with_matching_bytes() {
// 1. The drop filter (replicated verbatim from src/io/web_drop.rs)
// accepts ".dxf": rsplit_once('.') yields ("", "dxf").
let dropped = ".dxf"
.rsplit_once('.')
.is_some_and(|(_, extension)| {
matches!(extension.to_ascii_lowercase().as_str(), "dwg" | "dxf")
});
assert!(dropped, "drop filter accepts the dot-file '.dxf'");
// 2. The worker gate (and the real loader) also parse ".dxf" as DXF.
assert!(worker_accepts(".dxf"));
let document = OpenCADStudio::io::load_bytes(".dxf", FIXTURE_DXF.to_vec())
.expect("real loader opens '.dxf' as DXF");
// ...and it is a DXF source, so `source_is_dxf` says DXF (the autosave
// serializes DXF bytes).
assert!(document.dwg_source_version.is_none());
// 3. Worker-convention split: ".dxf" keeps "dxf" as its extension — the
// empty head falls back to the whole stored name as the stem.
let restored = recovered_name(".dxf");
assert_eq!(restored, ".dxf (recovered).dxf");
// 4. Real loader: DXF bytes under the recovered name now go to the DXF
// reader and OPEN — the restore door is unjammed.
assert!(worker_accepts(&restored));
assert!(
OpenCADStudio::io::load_bytes(&restored, FIXTURE_DXF.to_vec()).is_ok(),
"DXF bytes under {restored:?} must parse"
);
// And the dot-file's DWG twin keeps its DWG extension the same way.
assert_eq!(recovered_name(".dwg"), ".dwg (recovered).dwg");
}
/// FIXED (was BREAK): the "(recovered)" suffix used to STACK — the restored
/// tab's `current_path` becomes the recovered name, the next autosave round
/// snapshots it under THAT name, and the next restore appended another
/// marker ("x (recovered) (recovered).dwg"), one suffix per crash cycle,
/// unbounded. `recovered_name` now strips every trailing marker before
/// appending exactly one, so the name is idempotent across any number of
/// crash cycles.
#[test]
fn recovered_marker_never_stacks_across_crash_cycles() {
// A single cycle: the marker is appended once, then stays at one.
let mut name = "plan.dwg".to_string();
for cycle in 1..=50 {
name = recovered_name(&name);
assert_eq!(
name,
"plan (recovered).dwg",
"cycle {cycle}: the recovered name must be idempotent"
);
assert!(worker_accepts(&name), "{name:?} must stay parseable");
}
// Legacy stacked names (written by the OLD behaviour before the fix)
// collapse back to a single marker.
assert_eq!(
recovered_name("plan (recovered) (recovered).dwg"),
"plan (recovered).dwg"
);
assert_eq!(
recovered_name(&format!("plan{} (recovered).dwg", " (recovered)".repeat(40))),
"plan (recovered).dwg"
);
// Extensionless stacked names de-stack too, then gain the DXF default.
assert_eq!(recovered_name("plan (recovered)"), "plan (recovered).dxf");
// An embedded (non-suffix) marker is left alone.
assert_eq!(
recovered_name("(recovered) plan.dwg"),
"(recovered) plan (recovered).dwg"
);
// The cycle still re-offers after a crash (no recent save of its own
// name) — that property is unchanged, only the name growth is fixed.
assert!(newer_than_saved(0.0, None));
}
/// Names that survive intact: no extension → DXF fallback (matching how
/// autosave serializes untitled tabs as DXF via `source_is_dxf` →
/// `dwg_source_version.is_none()`), multi-dot keeps the final extension,
/// unicode is passed through, path separators are stripped from the head so
/// the result can never escape the display-name namespace (OPFS keys are
/// FNV hashes, never the name).
#[test]
fn benign_hostile_names_round_trip_parseable() {
for (input, expected, dxf_bytes) in [
// Extensionless names restore as DXF — what autosave serializes
// untitled tabs as (was ".dwg" under the old Path::extension split).
("Drawing1", "Drawing1 (recovered).dxf", true),
("a.b.dxf", "a.b (recovered).dxf", true),
("", " (recovered).dxf", false),
("plán.dwg", "plán (recovered).dwg", false),
("図面 1.dwg", "図面 1 (recovered).dwg", false),
] {
let got = recovered_name(input);
assert_eq!(got, expected);
assert!(worker_accepts(&got), "{got:?} must stay parseable");
// Real loader opens the name whenever the bytes match the extension
// it implies (DXF fixture bytes for .dxf outcomes).
if dxf_bytes {
assert!(
OpenCADStudio::io::load_bytes(&got, FIXTURE_DXF.to_vec()).is_ok(),
"{got}"
);
}
}
// Windows path semantics: separators in the stored name never survive
// into the recovered name as separators.
for hostile in ["..\\evil.dxf", "../evil.dxf", "a/b\\c.dwg"] {
let got = recovered_name(hostile);
assert!(
!got.contains('/') && !got.contains('\\'),
"recovered name must not carry path separators: {got:?}"
);
}
// A 4096-char name: stem grows, hash key stays 16 hex chars (see
// web_name_hash_redteam.rs) — no length-based failure.
let long = "x".repeat(4096 - ".dwg".len());
let got = recovered_name(&format!("{long}.dwg"));
assert!(worker_accepts(&got));
assert_eq!(got.len(), long.len() + " (recovered).dwg".len());
}
// ── newer_than_saved ────────────────────────────────────────────────────────
#[test]
fn newer_than_saved_hostile_timestamps() {
// Equal mtimes: same save round, not offered (existing behaviour).
assert!(!newer_than_saved(1000.0, Some(1000.0)));
// Negative mtimes compare numerically.
assert!(newer_than_saved(-5.0, Some(-10.0)));
assert!(!newer_than_saved(-10.0, Some(-5.0)));
// NaN autosave mtime: `NaN > x` is false — silently NOT offered. The
// snapshot survives (age never deletes), so worst case is a hidden
// snapshot, not a lost one. Deterministic, no poison.
assert!(!newer_than_saved(f64::NAN, Some(1000.0)));
// NaN saved mtime likewise hides the offer forever.
assert!(!newer_than_saved(1000.0, Some(f64::NAN)));
// Extremes behave numerically: +inf / f64::MAX are "newer" than anything
// finite; -inf is older than everything, including f64::MIN.
assert!(newer_than_saved(f64::MAX, Some(f64::MIN)));
assert!(newer_than_saved(f64::INFINITY, Some(f64::MAX)));
assert!(!newer_than_saved(f64::NEG_INFINITY, Some(f64::MIN)));
}
// ── cap_evictions ───────────────────────────────────────────────────────────
#[test]
fn cap_evictions_boundaries() {
// Empty: nothing kept, nothing evicted.
let (kept, evicted) = cap_evictions(Vec::new(), SNAPSHOT_CAP);
assert!(kept.is_empty() && evicted.is_empty());
// Exactly the cap: nothing evicted.
let entries: Vec<_> = (0..SNAPSHOT_CAP).rev().map(|i| entry(&format!("d{i}"), i as f64)).collect();
let (kept, evicted) = cap_evictions(entries, SNAPSHOT_CAP);
assert!(evicted.is_empty());
assert_eq!(kept.len(), SNAPSHOT_CAP);
assert_eq!(kept.first().unwrap().name, format!("d{}", SNAPSHOT_CAP - 1));
// Exactly cap+1: the single oldest is evicted, survivors newest-first.
let entries: Vec<_> = (0..=SNAPSHOT_CAP)
.map(|i| entry(&format!("d{i}"), i as f64))
.collect();
let (kept, evicted) = cap_evictions(entries, SNAPSHOT_CAP);
assert_eq!(evicted, ["d0"]);
assert_eq!(kept.last().unwrap().name, "d1");
assert_eq!(kept.first().unwrap().name, format!("d{SNAPSHOT_CAP}"));
// Unsorted input still yields newest-first offer order.
let (kept, _) = cap_evictions(
vec![entry("old", 1.0), entry("newest", 9.0), entry("mid", 5.0)],
SNAPSHOT_CAP,
);
assert_eq!(
kept.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
["newest", "mid", "old"]
);
// All-equal mtimes: the stable sort keeps index (push) order, `split_off`
// takes the tail, and the final `reverse()` flips it — so among equal
// mtimes the MOST RECENTLY INDEXED snapshot is deleted first. Arbitrary
// (ties carry no age signal) but deterministic.
let entries: Vec<_> = (0..SNAPSHOT_CAP + 2).map(|i| entry(&format!("e{i}"), 42.0)).collect();
let (kept, evicted) = cap_evictions(entries, SNAPSHOT_CAP);
assert_eq!(evicted, ["e17", "e16"]);
assert_eq!(kept.first().unwrap().name, "e0");
// Degenerate cap 0 evicts everything.
let (_, evicted) = cap_evictions(vec![entry("a", 1.0), entry("b", 2.0)], 0);
assert_eq!(evicted, ["a", "b"]); // oldest-first
}
/// NaN mtimes do NOT poison the choice into a panic or a wrong split — but
/// `total_cmp` ranks NaN ABOVE every finite mtime, so NaN entries sort as
/// "newest": they are always KEPT and cannot be evicted, while they push real
/// snapshots past the cap into eviction. `newer_than_saved(NaN, _)` then
/// refuses to offer them, so a NaN-mtime snapshot is undead: never offered,
/// never evicted, squatting one cap slot forever.
#[test]
fn cap_evictions_nan_mtimes_sort_as_newest_and_crowd_out_real_snapshots() {
let mut entries: Vec<_> = (0..SNAPSHOT_CAP)
.map(|i| entry(&format!("real{i}"), i as f64))
.collect();
entries.push(entry("nan", f64::NAN));
let (kept, evicted) = cap_evictions(entries, SNAPSHOT_CAP);
assert_eq!(kept.first().unwrap().name, "nan", "NaN sorts above +inf");
assert_eq!(evicted, ["real0"], "the oldest REAL snapshot pays for it");
assert!(!newer_than_saved(f64::NAN, Some(0.0)), "and is never offered");
// Mixed infinities stay ordered.
let (kept, _) = cap_evictions(
vec![entry("neg_inf", f64::NEG_INFINITY), entry("inf", f64::INFINITY), entry("zero", 0.0)],
SNAPSHOT_CAP,
);
assert_eq!(
kept.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
["inf", "zero", "neg_inf"]
);
}