* security: bound drawing document-model work and allocation (CWE-400/407)
Several document-model operations let crafted drawing data cause quadratic or
exponential work, or multiply retained allocations:
- Polyline grip generation rebuilt the whole segment vector inside the loop over
every vertex, so enumerating one large polyline's grips was quadratic. Compute
the segments once before the loop (row 35).
- Associative-array name sync searched the whole replacement vector for every
placement. Index replacements by placement coordinate once (last entry wins),
turning the per-item lookup O(1) (row 44).
- Dimension-extent bounds recursively expanded the referenced block without the
shared bounds cache the Insert path uses, so a branching or self-referencing
dimension block cost one pass per reference. Route it through the same
`(name, depth)` cache (row 37).
- Dynamic-block parsing parsed every graph-member occurrence into its own owned
parameter, so a graph repeating a member multiplied one record into gigabytes.
Deduplicate member handles before resolving them (row 7).
- Stretch-action application linearly searched the vertex list and cloned the
index vector for every selection occurrence. Index vertices by handle and skip
handles already handled in the action's selection (row 30).
New tests for polyline grips; all doc tests pass, clippy clean.
Addresses findings rows 7, 30, 35, 37, 44.
* fix: retain first dynamic stretch vertex selection
---------
Co-authored-by: skylartaylor <26588250+skylartaylor@users.noreply.github.com>
* security: bound geometry-kernel degree and work (CWE-407)
Several geometry routines let a crafted spline or region cause quadratic or
worse CPU work:
- B-spline basis evaluation is O(degree²) per sample and tessellation takes
O(degree) samples, so a HATCH/DXF spline edge declaring a very high degree
(DXF allows up to 100 000) turned a tiny spline into billions of iterations.
Add `MAX_DEGREE = 64` and treat higher-degree splines as invalid, so
`eval`/`tessellate` fall back to the control polygon. The render clip boundary
also rejects such degrees up front (rows 18, 28).
- `Spline::derivative` re-ran the O(knots) validity scan on every call, and
arc-length integration calls it once per sample, making a valid spline's
measurement quadratic. Split off `derivative_unchecked` and have integration
(validated once by its public entry points) use it (row 24).
- `infer_knot_param` matched each fit parameter against the whole knot vector
from the start. Both are ascending, so replace it with a linear merge (row 16).
- Fillet seed collection did not stop the enclosing run-pair loops when the
per-call candidate cap was hit, and refined duplicate candidates. Bound total
seeds across pairs and deduplicate before Newton refinement (row 36).
- Region grid intersection counted only distinct pairs against its budget, so a
long segment replicated across many cells re-visited the same pair unbounded.
Charge every candidate-pair visit against a budget (row 41).
New spline degree tests added; all geom and render tests pass, clippy clean.
Addresses findings rows 16, 18, 24, 28, 36, 41.
* fix: preserve spline knot and fillet search behavior
---------
Co-authored-by: skylartaylor <26588250+skylartaylor@users.noreply.github.com>
* security: do not follow directory symlinks in `cargo xtask stats` (CWE-400)
The stats walker descended with `Path::is_dir()`, which follows symlinks, and
kept no record of visited directories. A small acyclic graph of directory
aliases planted in a workspace package (for example through a contribution a
developer inspects) therefore caused exponentially repeated enumeration and file
reads, consuming CPU and I/O far beyond the repository's real size.
`walk` now inspects each entry's own `file_type()` and skips symlinks before
descending or reading, so directory aliases are never re-scanned. A traversal
budget (`MAX_ENTRIES`) bounds total work as defense in depth.
Addresses finding row 4.
* fix: report statistics traversal exhaustion
---------
Co-authored-by: skylartaylor <26588250+skylartaylor@users.noreply.github.com>
* security: write files atomically through an exclusive temp file (CWE-59, CWE-377)
Save, export, plot, autosave and the audit log each wrote their output by
putting bytes in a predictable sibling temporary path (`<path>.cadcraft-tmp`,
`<recovery>.tmp`, or the companion `.adt`) and renaming it over the real file.
Opening that pre-existing temporary path for a truncating write follows a
symlink planted there by another local user, letting them redirect the write
onto any file the victim can write before the rename.
Add a shared `atomic_write` helper that creates a fresh temporary file with
`create_new` (O_CREAT|O_EXCL) in the destination directory, writes through the
retained handle, flushes/syncs, and atomically renames it into place. An
existing entry (symlink or not) makes the exclusive create fail instead of
being followed. Route autosave, save, export, plot and the audit log through it.
The macOS CI cert importer likewise wrote the decoded PKCS#12 container to a
fixed name in a possibly shared temp directory; it now creates a private
per-run directory with `mktemp -d` and creates the file with noclobber.
Addresses findings rows 1, 25, 40 (CWE-59) and 19 (CWE-377).
* fix: preserve permissions during atomic replacement
* fix: restrict temporary permissions during exclusive creation
---------
Co-authored-by: skylartaylor <26588250+skylartaylor@users.noreply.github.com>
* Use chrono for UTC/calendar conversion instead of hand-rolled copies
Replaces the three civil_from_days copies (logging timestamp, Drawing
Recovery time, parity checklist date) with chrono as a workspace
dependency. Output formats are unchanged and pinned by the existing tests.
AGENTS.md now says time goes through chrono.
Fixes#1785
* Never panic on a clock outside chrono's range; keep 5-digit years unprefixed
chrono's From<SystemTime> unwraps, so a clock past year 262143 panicked
inside the logger. timestamp and xtask's date now use the fallible
DateTime::from_timestamp and read such a clock as the epoch, as the old
saturating code did. xtask's date also clamps a pre-epoch clock to
1970-01-01 again. Years past 9999 are written with {:04} like before,
because %Y would add a '+'. Tests cover all three cases.
* Don't build an unrepresentable SystemTime in the far-future test
UNIX_EPOCH + Duration::from_secs(u64::MAX / 2) overflows Windows'
SystemTime and panicked before timestamp() ran, failing the Windows
test job. Build it with checked_add and only assert where it exists.
* logging/autosave/parity: keep extended-year dates, no epoch fallback
Applies the stricter no-epoch-fallback rule (from wordcraft#3427 / filmcraft#2662,
superseding the earlier epoch-or-last-valid suggestion) so all sibling PRs agree:
a timestamp the old code converted past chrono's year 262143 range must keep its real
proleptic-Gregorian date, not collapse to 1970-01-01. Each site uses the 400-year
Gregorian cycle (146_097 days) with chrono as the only calendar logic: chrono converts
the day within one cycle, whole cycles carry in the year (i128, saturated into i64).
This also removes the panic FredApps flagged — `DateTime::<Utc>::from(SystemTime)` could
panic past chrono's range; `from_num_days_from_ce_opt` within one cycle never does.
Verified the cycle result equals the old formula across a wide range and at the extremes.
- apps/cadcraft/src/logging.rs `timestamp`: cycle `civil_from_days(u64)`; pre-1970 epoch
clamp and ms/time-of-day format kept. Pins: +10_000_000_000_000 s -> 318857-05-20T17:46:40.000Z
(was 1970-...); checked_add u64::MAX/2 s -> 292277026596-12-04T15:30:07.000Z (was epoch).
- crates/ui-egui/src/autosave.rs `utc`: cycle converter. Pins: utc(10_000_000_000_000)
= "318857-05-20 17:46"; utc(u64::MAX) = "584554051223-11-09 07:00" (was "1970-01-01 00:00").
- xtask/src/parity.rs `date`: cycle converter; pre-1970 epoch clamp kept. Pins:
day(115_740_740) = "318857-05-20"; checked_add u64::MAX/2 s -> "292277026596-12-04" (was epoch).
* Don't build a year-318857 SystemTime unchecked in the logging test
Windows' SystemTime only reaches about year 30828, so
UNIX_EPOCH + Duration::from_secs(10_000_000_000_000) panicked before
timestamp() ran and failed the Windows test job. Build it with
checked_add and assert where the platform can hold it. The year-10000
case fits everywhere and stays unconditional.
* Name the 400-year range extension as the one exception to the time rule
The rule said never to hand-roll calendar math, but the range fix
(shifting by whole 400-year Gregorian cycles so dates past chrono's year
range keep their old output) is cycle arithmetic, so the rule and the code
disagreed. The rule now names that exception: the library still computes
month, day and time, and only whole cycles are carried in the year.
* Say the library computes month and day; time-of-day is plain arithmetic
Narrows the range-extension wording: the date library computes the
calendar fields, and splitting seconds into hours, minutes and seconds
is ordinary arithmetic, which is what the code does.
Calls storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with secrets: inherit. Adds SonarCloud badge to README where missing and
removes the redundant sonar-project.properties (config now passed by the
reusable workflow).
* ci: refactor workflows to use reusable artcraft-common-actions
* ci: point reusable workflows to storytold/craft-common-actions
* ci: pin storytold/craft-common-actions to commit 27a978f and pass secrets explicitly
* ci: use @main (unpinned) for craft-common-actions with explanation comment
* DIMANGULAR: accept polyline segments (fixes#10)
Picking a side of a rectangle or a PLINE segment was rejected with
"Select a line or an arc." because only LINE and ARC entities were
accepted. The picked object is now resolved to the segment under the
cursor: straight polyline segments work like lines and arc segments
like arcs.
* Redraw edits made while a command is still running (fixes#4)
LINE and PLINE add geometry on every point, but the canvas only rebuilt
its display list when the drawing revision or the document pointer
changed. The revision was bumped when a command finished, and the
pointer changed only on the first copy-on-write edit, so only the first
segment appeared until the command ended. Session::feed now bumps the
revision after each input once the running command has changed the
drawing.
* Fix#14: include DWG in the Open drawing filter
* Blocks window: click a block to insert it (#8)
Each block name in the Blocks window is now a button. Clicking it starts INSERT with that block already chosen, so the command line asks for the insertion point.
* SCALE: Reference option (#17)
SCALE > Reference printed "not available yet". It now asks for the reference length (typed, or two points) and the new length (typed, or a point measured from the base point), and scales by new / reference. Zero, negative or non-finite lengths are rejected and asked again.
* Print and Ctrl+P ask where to save the PDF (#5)
PLOT/EXPORTPDF started from the menu, the toolbar, Ctrl+P or the command line had no path,
so the PDF was built in memory and dropped. They now open the save dialog (PDF filter first)
and write the file there. JSON calls from scripts, the control channel and MCP still never
open a dialog. Ctrl+P was shown in the menu but not bound; it is now.
* Scripts: split a line at keyword prompts so POLYGON 6 200,20 I 15 works (#43)
* Layer Properties Manager: stop the window growing every frame (fixes#29)
The vertical separator between the filter tree and the table takes all the
height it is offered, and a resizable window offers its previous height, so
the window grew 30px per frame until it filled the screen. Cap the row at the
table's fixed height. Regression test runs the dialog headless for 30 frames
and checks the height stays put.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* ui.render: fit the drawing and return pngBase64 like the headless render (#49, #50)
* Linux: default to XWayland for file drag-and-drop on Wayland desktops
* Fonts: per-character fallback, FONTALT and .ttc for CJK text in SHX styles (#130)
CJK text in a style that uses an SHX font (romans.shx + chineset.shx big font)
drew every ideograph as an empty box: the SHX name resolves to our stroke font,
which has no CJK glyphs, and the font scan skipped .ttc collections, where most
CJK system fonts live.
- Per-character fallback: a character the text's font lacks (stroke font or
TrueType) is drawn from an installed font that has it, checked by cmap.
Wide-coverage fonts go first (Noto Sans CJK, Source Han, WenQuanYi, Droid
Sans Fallback, PingFang, Microsoft JhengHei/YaHei, MS Gothic, ...), regular
weights before others. Fallback glyphs are sized like TrueType text (cap
height = text height). Lookups are cached; the search is bounded (24 files,
160 MiB, 256 faces per character, files over 96 MiB never read) and skips
spaces, controls and private-use code points. No fallback: the box as before.
- FONTALT (sysvar, seeded from CADCRAFT_FONTALT): font used for a style font
that can't be found (an SHX file, a missing TTF). Empty = our stroke font.
- FONTFALLBACK (sysvar, seeded from CADCRAFT_FONTFALLBACK): fonts tried first
for missing characters, e.g. "Noto Sans CJK TC".
- .ttc/.otc are scanned; TextFont::Outline carries a ttf::Face (bytes + face
index). Fonts are also found by family name among files with a similar
stem, so "Noto Sans CJK TC" picks face 3 of NotoSansCJK-Regular.ttc.
- Cap height falls back to the height of "H" when OS/2 has none (DejaVu
Sans), which fixes ttf_tests::system_font_outlines_when_available and
render's truetype_text_is_filled_or_outlined on machines without Arial.
- README: a Fonts section for the two settings; ROADMAP M4 note.
Native SHX / big-font rendering stays on the roadmap (M4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Fonts: cap the total bytes of system font files loaded from disk
A drawing naming many text styles could otherwise load every installed font
into memory through family-name lookups.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pan with a two-finger trackpad swipe; keep wheel and pinch zoom
Trackpad two-finger swipes arrive as scroll events, and the canvas turned
every scroll into a zoom, so trackpad users had no realtime pan (middle-drag
needs a middle button).
Scroll now follows the device: precise point deltas (trackpad, Magic Mouse)
pan the view by x and y; notched line deltas (mouse wheel) zoom about the
cursor as before. Pinch and Cmd+scroll still zoom through zoom_delta, and
middle-drag still pans.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uMCkRAB8DMd8MEmoY9Vyr
* Add Tru10 to contributors/people.toml
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uMCkRAB8DMd8MEmoY9Vyr
* Trackpad pan: only on macOS, where point deltas mean a trackpad
Browsers and Wayland smooth-scroll mice report ordinary wheels in points too,
so the wheel keeps zooming there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep arc-length dimensions as arc-length through DXF save and reopen (#100)
* PLINE: Halfwidth is centre-to-edge, and Width answers taper the next segment (fixes#83, #104)
Interactive PLINE kept one width value: Halfwidth answers were stored as
the total width, and the ending-width answer overwrote the starting one,
so a taper became a constant width. The next segment's starting and
ending widths are now tracked separately, Halfwidth answers are doubled,
and each new segment (including the closing one) gets its widths on its
first vertex; later segments are uniform at the ending width, as in
AutoCAD. Uniform polylines are still stored as const_width, so their DXF
output is unchanged.
Fixes#83. Fixes#104.
* Arc-length dimensions: write a standard aligned record plus CADCraft xdata
DXF has no arc-length DIMENSION type, so write type 1 and mark the kind and
arc centre in CADCRAFT xdata (like ASSOC). Other programs read an aligned
dimension; CADCraft restores the arc length, through DXF and DWG.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Desktop: write log records to standard error and a rotating log file
The desktop app installed no logger, so every log::warn!/log::error!/
log::info! in the workspace was discarded: a broken app icon, the GPU
canvas set-up, the engine's command-line echo at debug level. A launch
from a desktop menu has no terminal either, so there was nothing to
attach to a bug report.
apps/cadcraft/src/logging.rs (no new dependency):
- standard error plus <settings dir>/logs/cadcraft.log; each launch
rotates the previous log to cadcraft.1.log and .2.log, so the log of a
run that crashed survives the next start; the file is capped at 16 MiB
- records logged before the settings directory is known are buffered
(bounded) and written once the file is attached
- default levels: info for cadcraft*, warn for everything else;
RUST_LOG replaces them with env_logger-style directives
- never panics: an unusable directory or a failed write leaves standard
error as the only sink; a poisoned lock is tolerated
CADCraft had no per-user directory yet. config_dir in main.rs adds one:
CADCRAFT_CONFIG_DIR, else $XDG_CONFIG_HOME/cadcraft or ~/.config/cadcraft
(Linux, BSDs), ~/Library/Application Support/CADCraft (macOS),
%APPDATA%\CADCraft (Windows).
The logger is installed first in main and the file is opened after
argument parsing (--version leaves no file). The control server's
eprintln!s now go through the logger. A --control or
CADCRAFT_CONTROL_PORT value that is not a port is now logged instead of
silently leaving the control channel off. Documented in README.md
(Quick start > Logs).
---------
Co-authored-by: SBaksa <sabaksa11@gmail.com>
Co-authored-by: DWAA1660 <dwatnip123@gmail.com>
Co-authored-by: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com>
Co-authored-by: lloyd <34131158+LloydNicholson@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: vangel76 <vangel1976@googlemail.com>
Co-authored-by: Brandon Thomas <echelon@gmail.com>
Co-authored-by: Tru10 <133776756+Tru10@users.noreply.github.com>
Co-authored-by: Gert Pellin <gert@pellin.be>