From caea05eff8d2044136d4befe499db7b93b4dcd03 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 07:59:58 -0400 Subject: [PATCH 1/7] Use jiff for UTC/calendar conversion instead of hand-rolled copies This repo already uses jiff (ui-egui, for the system time zone), so the hand-rolled Howard Hinnant civil/days-from-civil copies move to jiff rather than pulling in a second time crate. jiff is lifted to a workspace dependency: - crates/core/src/time.rs: parse_rfc3339's days_from_civil and civil_from_unix - xtask/src/local.rs: rfc3339 (feed timestamps) ui-egui now takes jiff from the workspace. core keeps only civil-date math (no time zone), so the wasm build is unaffected. Output and parsing semantics are unchanged and pinned by the existing tests (RFC 3339 parsing, leap days, day rollover, the feed's YYYY-MM-DDTHH:MM:SSZ). AGENTS.md now says time goes through jiff. Follow-up to storytold/cadcraft#1785 --- AGENTS.md | 2 ++ Cargo.lock | 4 ++++ Cargo.toml | 2 ++ crates/core/Cargo.toml | 2 ++ crates/core/src/time.rs | 38 ++++++++++++++++---------------------- crates/ui-egui/Cargo.toml | 2 +- xtask/Cargo.toml | 3 +++ xtask/src/local.rs | 17 +++++------------ 8 files changed, 35 insertions(+), 35 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 43670025..316c267d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,6 +113,8 @@ only; English where there is none): never bundle a CJK font, they are 10 MB and GitHub release JSON fixtures (small, committed under `crates/core/tests/fixtures/`). 5. When fetching anything, use a generic `ArtCraft-Launcher/` User-Agent and never put a person's name, email or other personal details in requests. +6. **Time goes through `jiff`** (workspace dependency). Never hand-roll UTC/calendar conversion + (days-to-date algorithms, leap-year math); a module owns only its output format string. ## 3. Before you finish a task diff --git a/Cargo.lock b/Cargo.lock index b381bfc1..e656d002 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -303,6 +303,7 @@ dependencies = [ name = "artcraft-launcher-core" version = "0.6.1" dependencies = [ + "jiff", "semver", "serde", "serde_json", @@ -5875,6 +5876,9 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" version = "0.6.1" +dependencies = [ + "jiff", +] [[package]] name = "yoke" diff --git a/Cargo.toml b/Cargo.toml index 673fdbac..805f2a7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" semver = { version = "1", features = ["serde"] } log = "0.4" +# All date/time conversion goes through jiff (no hand-rolled calendar code; AGENTS.md). +jiff = "0.2" [profile.dev.package."*"] opt-level = 2 diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 4806c1ce..c518d780 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -14,3 +14,5 @@ workspace = true serde = { workspace = true } serde_json = { workspace = true } semver = { workspace = true } +# Calendar conversion (jiff); see AGENTS.md. Only civil-date math is used, no time zone. +jiff = { workspace = true } diff --git a/crates/core/src/time.rs b/crates/core/src/time.rs index 22b580f4..34c19323 100644 --- a/crates/core/src/time.rs +++ b/crates/core/src/time.rs @@ -1,4 +1,5 @@ -//! Just enough calendar to read GitHub's timestamps and show them, without a date crate. +//! Just enough calendar to read GitHub's timestamps and show them (the conversion goes through +//! jiff; this module owns only the parsing and the output format strings). //! //! # Internationalisation //! [`format_ago`] and [`format_date`] are English-only fallbacks. Translatable UI must use @@ -64,32 +65,25 @@ pub fn parse_rfc3339(text: &str) -> Option { } _ => return None, }; - Some(days_from_civil(y, mo, d) * 86_400 + h * 3600 + mi * 60 + s - offset) + Some(days_from_civil(y, mo, d)? * 86_400 + h * 3600 + mi * 60 + s - offset) } -/// Days since 1970-01-01 (Howard Hinnant's algorithm). -fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { - let y = if m <= 2 { y - 1 } else { y }; - let era = y.div_euclid(400); - let yoe = y - era * 400; - let mp = (m + 9) % 12; - let doy = (153 * mp + 2) / 5 + d - 1; - let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; - era * 146_097 + doe - 719_468 +/// Days since 1970-01-01 (through jiff's civil calendar). A day past the month's length rolls over +/// the way the old Hinnant arithmetic did (e.g. `2026-02-30` → `2026-03-02`). `None` for a year +/// outside jiff's range. +fn days_from_civil(y: i64, m: i64, d: i64) -> Option { + let first = jiff::civil::Date::new(i16::try_from(y).ok()?, i8::try_from(m).ok()?, 1).ok()?; + let date = first.checked_add(jiff::SignedDuration::from_hours(d.checked_sub(1)?.checked_mul(24)?)).ok()?; + Some(date.duration_since(jiff::civil::Date::constant(1970, 1, 1)).as_secs() / 86_400) } -/// (year, month, day) for a Unix time. +/// (year, month, day) for a Unix time (UTC). A time outside jiff's calendar range reads as the +/// epoch rather than panicking. pub fn civil_from_unix(secs: i64) -> (i64, u32, u32) { - let z = secs.div_euclid(86_400) + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + i64::from(m <= 2); - (y, u32::try_from(m).unwrap_or(1), u32::try_from(d).unwrap_or(1)) + let epoch = jiff::civil::Date::constant(1970, 1, 1); + let whole_days = jiff::SignedDuration::from_secs(secs.div_euclid(86_400).saturating_mul(86_400)); + let date = epoch.checked_add(whole_days).unwrap_or(epoch); + (i64::from(date.year()), u32::try_from(date.month()).unwrap_or(1), u32::try_from(date.day()).unwrap_or(1)) } const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 235558cd..aebc6962 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -24,7 +24,7 @@ sys-locale = "0.3" # Finding the Simplified Chinese face in a system font collection; egui already uses it. skrifa = { version = "0.44", default-features = false, features = ["std"] } # The system time zone, so dates read as this computer's calendar; already in the desktop build. -jiff = "0.2" +jiff = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] # The browser's time zone, for the same dates. diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index f027cec0..941b3d56 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -7,3 +7,6 @@ publish = false [lints] workspace = true + +[dependencies] +jiff = { workspace = true } diff --git a/xtask/src/local.rs b/xtask/src/local.rs index f818d21d..eae1fea3 100644 --- a/xtask/src/local.rs +++ b/xtask/src/local.rs @@ -493,20 +493,13 @@ fn unix_now() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0)) } -/// `2026-10-10T12:00:00Z` (civil-from-days, Howard Hinnant's algorithm). +/// `2026-10-10T12:00:00Z` (through jiff's civil calendar). fn rfc3339(secs: i64) -> String { - let days = secs.div_euclid(86_400); let rem = secs.rem_euclid(86_400); - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z.rem_euclid(146_097); - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + i64::from(m <= 2); - format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60) + let epoch = jiff::civil::Date::constant(1970, 1, 1); + let whole_days = jiff::SignedDuration::from_secs(secs.div_euclid(86_400).saturating_mul(86_400)); + let date = epoch.checked_add(whole_days).unwrap_or(epoch); + format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", date.year(), date.month(), date.day(), rem / 3600, rem % 3600 / 60, rem % 60) } // ---- versions ----------------------------------------------------------------------------------- From e61e2407d76bfbf2f7424730bcfc3909d13092ac Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 09:14:03 -0400 Subject: [PATCH 2/7] Lock in the epoch fallback for clocks outside jiff's range The jiff date conversions already fall back to the epoch instead of panicking, and format years with {:04} (rfc3339) or a plain integer (format_date), unchanged from the old hand-rolled code. Add tests that civil_from_unix(i64::MAX/MIN) and rfc3339(i64::MAX) stay on the epoch date and never panic. --- crates/core/src/time.rs | 3 +++ xtask/src/local.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/crates/core/src/time.rs b/crates/core/src/time.rs index 34c19323..6295526e 100644 --- a/crates/core/src/time.rs +++ b/crates/core/src/time.rs @@ -155,6 +155,9 @@ mod tests { fn shows_dates_people_read() { assert_eq!(format_date(1_791_471_170), "Oct 8, 2026"); assert_eq!(civil_from_unix(951_782_400), (2000, 2, 29)); + // A time past jiff's calendar range reads as the epoch instead of panicking. + assert_eq!(civil_from_unix(i64::MAX), (1970, 1, 1)); + assert_eq!(civil_from_unix(i64::MIN), (1970, 1, 1)); let now = 1_791_471_170; assert_eq!(format_ago(now - 5, now), "just now"); assert_eq!(format_ago(now - 600, now), "10 min ago"); diff --git a/xtask/src/local.rs b/xtask/src/local.rs index eae1fea3..1c710842 100644 --- a/xtask/src/local.rs +++ b/xtask/src/local.rs @@ -685,6 +685,8 @@ mod tests { fn dates_and_versions() { assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); assert_eq!(rfc3339(1_791_500_000), "2026-10-08T22:53:20Z"); + // A time past jiff's calendar range reads as the epoch date instead of panicking. + assert!(rfc3339(i64::MAX).starts_with("1970-01-01T")); assert_eq!(compare_versions("0.10.0", "0.9.0"), std::cmp::Ordering::Greater); assert_eq!(compare_versions("1.0.0", "1.0.0-rc.1"), std::cmp::Ordering::Greater); assert!(parse_version("1.2").is_none() && parse_version(".building-1.2.3").is_none()); From 0091a46d3be62e8e3f91e4ae0dd1a4f448a6e54b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 17:22:06 -0400 Subject: [PATCH 3/7] time: keep old UTC output past jiff's narrow civil range MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `civil_from_unix` (core) and `rfc3339` (xtask) took `i64` Unix seconds, which the old hand-rolled Hinnant code converted across the whole `i64` range. The jiff rewrite built the date with `epoch.checked_add(whole_days).unwrap_or(epoch)`, but jiff's civil calendar only spans years -9999..=9999 — far narrower than chrono's — so any instant past year 9999 silently became the epoch, changing existing output. `i64::MAX` used to read `Dec 4, 292277026596` / `292277026596-12-04T15:30:07Z`, and `i64::MIN` `Jan 27, -292277022657`, not 1970. Fix: move the instant into jiff's range by whole 400-year Gregorian cycles (146_097 days) before converting, then restore the real year afterwards. `rest` is always under one cycle, so the in-range date lands in 1970..=2369 (well inside jiff) and `rest * 86_400` can't overflow; the year is restored through `i128` so `cycles * 400` is exact at the `i64` extremes. jiff stays the only calendar logic (it does the month/day); the cycle count just shifts the year. No epoch fallback for any value the old code converted. core still builds for wasm32. Tests now pin the old output instead of the epoch: - core civil_from_unix(i64::MAX) == (292277026596, 12, 4), civil_from_unix(i64::MIN) == (-292277022657, 1, 27), civil_from_unix(253_402_300_800) == (10000, 1, 1) - xtask rfc3339(i64::MAX) == "292277026596-12-04T15:30:07Z", rfc3339(i64::MIN) == "-292277022657-01-27T08:29:52Z", rfc3339(253_402_300_800) == "10000-01-01T00:00:00Z" --- crates/core/src/time.rs | 31 +++++++++++++++++++++++-------- xtask/src/local.rs | 25 +++++++++++++++++++------ 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/core/src/time.rs b/crates/core/src/time.rs index 6295526e..347fe3df 100644 --- a/crates/core/src/time.rs +++ b/crates/core/src/time.rs @@ -77,13 +77,23 @@ fn days_from_civil(y: i64, m: i64, d: i64) -> Option { Some(date.duration_since(jiff::civil::Date::constant(1970, 1, 1)).as_secs() / 86_400) } -/// (year, month, day) for a Unix time (UTC). A time outside jiff's calendar range reads as the -/// epoch rather than panicking. +/// (year, month, day) for a Unix time (UTC). jiff's civil calendar only spans years -9999..=9999, +/// far narrower than the whole `i64` the old hand-rolled Hinnant code converted, so the instant is +/// first moved into range by whole 400-year Gregorian cycles (the calendar repeats every 400 years +/// = 146_097 days) and the real year restored afterwards. jiff still does the month/day; the cycle +/// count only shifts the year, keeping every `i64` exact (e.g. `i64::MAX` → year 292277026596, +/// `i64::MIN` → year -292277022657), with no epoch fallback for a value the old code converted. pub fn civil_from_unix(secs: i64) -> (i64, u32, u32) { let epoch = jiff::civil::Date::constant(1970, 1, 1); - let whole_days = jiff::SignedDuration::from_secs(secs.div_euclid(86_400).saturating_mul(86_400)); - let date = epoch.checked_add(whole_days).unwrap_or(epoch); - (i64::from(date.year()), u32::try_from(date.month()).unwrap_or(1), u32::try_from(date.day()).unwrap_or(1)) + let days = secs.div_euclid(86_400); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest` is in `0..146_097` (under one 400-year cycle), so `epoch + rest days` always lands in + // 1970..=2369 — comfortably inside jiff's range — and `rest * 86_400` never overflows. + let date = epoch.checked_add(jiff::SignedDuration::from_secs(rest * 86_400)).unwrap_or(epoch); + // Restore the real year through `i128` so `cycles * 400` can't overflow at the `i64` extremes. + let y = i128::from(date.year()) + i128::from(cycles) * 400; + let year = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }); + (year, u32::try_from(date.month()).unwrap_or(1), u32::try_from(date.day()).unwrap_or(1)) } const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; @@ -155,9 +165,14 @@ mod tests { fn shows_dates_people_read() { assert_eq!(format_date(1_791_471_170), "Oct 8, 2026"); assert_eq!(civil_from_unix(951_782_400), (2000, 2, 29)); - // A time past jiff's calendar range reads as the epoch instead of panicking. - assert_eq!(civil_from_unix(i64::MAX), (1970, 1, 1)); - assert_eq!(civil_from_unix(i64::MIN), (1970, 1, 1)); + // Year 10000 is past jiff's own calendar range, but the 400-year cycle reduction keeps the + // old conversion (jiff spans only -9999..=9999). + assert_eq!(civil_from_unix(253_402_300_800), (10000, 1, 1)); + // The `i64` extremes stay the dates the old Hinnant code produced, not the epoch. + assert_eq!(civil_from_unix(i64::MAX), (292_277_026_596, 12, 4)); + assert_eq!(civil_from_unix(i64::MIN), (-292_277_022_657, 1, 27)); + assert_eq!(format_date(i64::MAX), "Dec 4, 292277026596"); + assert_eq!(format_date(i64::MIN), "Jan 27, -292277022657"); let now = 1_791_471_170; assert_eq!(format_ago(now - 5, now), "just now"); assert_eq!(format_ago(now - 600, now), "10 min ago"); diff --git a/xtask/src/local.rs b/xtask/src/local.rs index 1c710842..80ab42f1 100644 --- a/xtask/src/local.rs +++ b/xtask/src/local.rs @@ -493,13 +493,23 @@ fn unix_now() -> i64 { SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(0)) } -/// `2026-10-10T12:00:00Z` (through jiff's civil calendar). +/// `2026-10-10T12:00:00Z` (through jiff's civil calendar). jiff spans only years -9999..=9999, far +/// narrower than the whole `i64` the old hand-rolled Hinnant code converted, so the instant is +/// moved into range by whole 400-year Gregorian cycles (146_097 days) and the real year restored +/// afterwards. jiff still does the month/day; the cycle count only shifts the year, keeping every +/// `i64` exact (e.g. `i64::MAX` → year 292277026596) with no epoch fallback. fn rfc3339(secs: i64) -> String { let rem = secs.rem_euclid(86_400); let epoch = jiff::civil::Date::constant(1970, 1, 1); - let whole_days = jiff::SignedDuration::from_secs(secs.div_euclid(86_400).saturating_mul(86_400)); - let date = epoch.checked_add(whole_days).unwrap_or(epoch); - format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", date.year(), date.month(), date.day(), rem / 3600, rem % 3600 / 60, rem % 60) + let days = secs.div_euclid(86_400); + let (cycles, rest) = (days.div_euclid(146_097), days.rem_euclid(146_097)); + // `rest` is in `0..146_097` (under one 400-year cycle), so `epoch + rest days` lands in + // 1970..=2369 (inside jiff's range) and `rest * 86_400` never overflows. + let date = epoch.checked_add(jiff::SignedDuration::from_secs(rest * 86_400)).unwrap_or(epoch); + // Restore the real year through `i128` so `cycles * 400` can't overflow at the `i64` extremes. + let y = i128::from(date.year()) + i128::from(cycles) * 400; + let y = i64::try_from(y).unwrap_or(if y < 0 { i64::MIN } else { i64::MAX }); + format!("{y:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", date.month(), date.day(), rem / 3600, rem % 3600 / 60, rem % 60) } // ---- versions ----------------------------------------------------------------------------------- @@ -685,8 +695,11 @@ mod tests { fn dates_and_versions() { assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); assert_eq!(rfc3339(1_791_500_000), "2026-10-08T22:53:20Z"); - // A time past jiff's calendar range reads as the epoch date instead of panicking. - assert!(rfc3339(i64::MAX).starts_with("1970-01-01T")); + // Year 10000 and the `i64` extremes are past jiff's own calendar range (-9999..=9999), but + // the 400-year cycle reduction keeps the dates the old Hinnant code produced, not the epoch. + assert_eq!(rfc3339(253_402_300_800), "10000-01-01T00:00:00Z"); + assert_eq!(rfc3339(i64::MAX), "292277026596-12-04T15:30:07Z"); + assert_eq!(rfc3339(i64::MIN), "-292277022657-01-27T08:29:52Z"); assert_eq!(compare_versions("0.10.0", "0.9.0"), std::cmp::Ordering::Greater); assert_eq!(compare_versions("1.0.0", "1.0.0-rc.1"), std::cmp::Ordering::Greater); assert!(parse_version("1.2").is_none() && parse_version(".building-1.2.3").is_none()); From a483ae81f64ed0ee1b4db9262d3aa8e453f4ea8b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 17:51:41 -0400 Subject: [PATCH 4/7] security: confine release/feed download URLs to the repository and bind artifact version Download URLs were accepted on a raw starts_with(prefix) check. A value like .../releases/download/../../../ATTACKER/REPO/releases/download/v99/app shares the prefix textually but its interpreted path escapes into another repository (CWE-180), and the Linux AppImage self-update then downloads and executes those bytes. - Add release::download_url_under / download_url_under_mirror, which require the text after the prefix to be exactly /: two non-empty segments, no traversal (./..), no extra slashes, no query/fragment/backslash, and no percent-encoded separators (%2f/%5c). release_from_value and FeedRelease::to_release share it. - Bind the installed artifact to the release that authorized it: before download, bind_artifact_version rejects an artifact whose filename-encoded version or URL release tag disagrees with release.version, so a feed cannot advertise a new version while shipping an older official build and persist a false version. Addresses findings: release.rs CWE-180, feed.rs CWE-180, platform/install version binding. --- crates/core/src/feed.rs | 17 +++++++-- crates/core/src/release.rs | 71 +++++++++++++++++++++++++++++++++++- crates/native/src/install.rs | 64 ++++++++++++++++++++++++++++++++ 3 files changed, 148 insertions(+), 4 deletions(-) diff --git a/crates/core/src/feed.rs b/crates/core/src/feed.rs index 4d24d8f2..deb5d9bb 100644 --- a/crates/core/src/feed.rs +++ b/crates/core/src/feed.rs @@ -186,13 +186,12 @@ impl FeedRelease { /// when it doesn't hold up (no tag, or not a version). fn to_release(&self, repo: &str, mirror: Option<&str>) -> Option { let version = version::parse(&self.tag)?; - let prefix = release::download_prefix(repo); - let allowed = |url: &str| url.starts_with(&prefix) || mirror.is_some_and(|m| url.starts_with(m) && !url.contains("..")); + let allowed = |url: &str| release::download_url_under(url, &release::download_prefix(repo)) || mirror.is_some_and(|m| release::download_url_under_mirror(url, m)); let releases_page = format!("https://github.com/{repo}/releases/"); let assets = self .assets .iter() - .filter(|(name, _, url, _)| release::valid_file_name(name) && allowed(url) && !url.contains(['?', '#', '\\'])) + .filter(|(name, _, url, _)| release::valid_file_name(name) && allowed(url)) .map(|(name, size, url, sha)| Asset { name: name.clone(), size: *size, @@ -564,6 +563,18 @@ mod tests { assert_eq!(feed.answer(app("photocraft"), NOW), FeedAnswer::AskGitHub); } + #[test] + fn a_feed_url_cannot_traverse_out_of_the_repository() { + // The feed advertises a legitimate tag but points the asset at another repository by + // climbing out with `../` after the approved prefix (CWE-180). + let escaped = sample().replace( + "https://github.com/storytold/photocraft/releases/download/v0.6.0/photocraft-0.6.0-macos-universal.dmg", + "https://github.com/storytold/photocraft/releases/download/../../../../attacker/repo/releases/download/v99/photocraft-0.6.0-macos-universal.dmg", + ); + let FeedAnswer::Fresh(Some(r)) = Feed::parse(&escaped).unwrap().answer(app("photocraft"), NOW) else { panic!() }; + assert!(r.assets.is_empty(), "the traversing download must be rejected"); + } + #[test] fn a_local_mirror_is_trusted_only_when_asked_for_and_never_goes_stale() { const MIRROR: &str = "http://127.0.0.1:8787/"; diff --git a/crates/core/src/release.rs b/crates/core/src/release.rs index f975d176..c0ed9c31 100644 --- a/crates/core/src/release.rs +++ b/crates/core/src/release.rs @@ -73,6 +73,54 @@ pub fn download_prefix(repo: &str) -> String { format!("https://github.com/{repo}/releases/download/") } +/// Whether `url` is a download that truly belongs to `repo`. +/// +/// A raw `starts_with(prefix)` check is not enough: a value such as +/// `https://github.com/storytold/craft-launcher/releases/download/../../../ATTACKER/REPO/releases/download/v1/x` +/// shares the prefix textually, yet its interpreted path escapes the repository. The link is +/// accepted only when the text after the prefix is exactly `/` — two non-empty path +/// segments with no traversal (`.`/`..`), no additional slashes, no query or fragment, and no +/// backslash or percent-encoded separators that a client could later re-interpret. +pub fn download_url_under(url: &str, prefix: &str) -> bool { + let Some(rest) = url.strip_prefix(prefix) else { return false }; + download_suffix_ok(rest) +} + +/// Whether `url` sits under a developer mirror `base` (ending in `/`) without escaping it. +pub fn download_url_under_mirror(url: &str, base: &str) -> bool { + let Some(rest) = url.strip_prefix(base) else { return false }; + // A mirror serves `/` just like GitHub, but we only require that it can't climb out + // of its own folder; its layout is otherwise the developer's business. + !rest.is_empty() && !url.contains(['?', '#', '\\']) && !contains_traversal(rest) && !contains_encoded_separator(rest) +} + +/// `/`: exactly two non-empty segments, no traversal, no re-interpretable separators. +fn download_suffix_ok(rest: &str) -> bool { + if rest.contains(['?', '#', '\\']) || contains_encoded_separator(rest) { + return false; + } + let mut parts = rest.split('/'); + let (Some(tag), Some(name), None) = (parts.next(), parts.next(), parts.next()) else { return false }; + !tag.is_empty() + && tag != "." + && tag != ".." + && tag.len() <= 64 + && !tag.contains('\\') + && valid_file_name(name) +} + +/// Any `.` or `..` path segment that could climb out of the repository. +fn contains_traversal(rest: &str) -> bool { + rest.split('/').any(|seg| seg == "." || seg == "..") +} + +/// Percent-encoded slash or backslash (`%2f`, `%5c`): a client could decode these back into +/// separators after the check, so a confined URL must not contain them. +fn contains_encoded_separator(rest: &str) -> bool { + let bytes = rest.as_bytes(); + bytes.windows(3).any(|w| w[0] == b'%' && matches!(&w[1..].to_ascii_lowercase()[..], b"2f" | b"5c")) +} + /// Reads `GET /repos//releases/latest` (or one element of `/releases`). pub fn parse_github_release(json: &str, repo: &str) -> Result { let v: serde_json::Value = serde_json::from_str(json).map_err(|e| format!("unreadable answer from GitHub ({e})"))?; @@ -119,7 +167,7 @@ fn release_from_value(v: &serde_json::Value, repo: &str) -> Result", REPO).is_err()); } + #[test] + fn traversal_cannot_escape_the_repository() { + // Raw-prefix matches but the interpreted path climbs into another repository (CWE-180). + for url in [ + "https://github.com/storytold/photocraft/releases/download/../../../../attacker/repo/releases/download/v99/photocraft-99.0.0-linux-x86_64.AppImage", + "https://github.com/storytold/photocraft/releases/download/v1/../../../attacker/repo/x.dmg", + "https://github.com/storytold/photocraft/releases/download/./v1/x.dmg", + "https://github.com/storytold/photocraft/releases/download/v1/sub/x.dmg", + "https://github.com/storytold/photocraft/releases/download/v1%2f..%2f..%2fx.dmg", + "https://github.com/storytold/photocraft/releases/download/v1/x%2fy.dmg", + ] { + let prefix = download_prefix(REPO); + assert!(!download_url_under(url, &prefix), "{url}"); + let r = parse_github_release(&api_json(url), REPO).unwrap(); + assert!(r.assets.is_empty(), "{url}"); + } + // A plain, confined download still passes. + let prefix = download_prefix(REPO); + assert!(download_url_under("https://github.com/storytold/photocraft/releases/download/v0.5.0/photocraft-0.5.0-macos-universal.dmg", &prefix)); + } + #[test] fn list_picks_the_newest_stable_release() { let json = r#"[ diff --git a/crates/native/src/install.rs b/crates/native/src/install.rs index de59e7a0..92c8d840 100644 --- a/crates/native/src/install.rs +++ b/crates/native/src/install.rs @@ -81,6 +81,7 @@ pub fn install_at( { return Err(format!("{} is running. Quit it, then try again.", app.name)); } + bind_artifact_version(app, release, asset)?; if !job.replace && let Some(inst) = existing && let (Some(rel_v), Some(inst_v)) = (release.version.as_ref(), inst.version.as_ref()) @@ -147,6 +148,38 @@ pub fn install_at( result.map_err(|e| if e == CANCELLED { INSTALL_CANCELLED.to_string() } else { e }) } +/// Rejects an artifact whose own identity disagrees with the release that authorized it. +/// +/// A feed or GitHub converter supplies the release version, the asset filename, and the download +/// URL independently. The downgrade guard and the persisted record both trust `release.version`, +/// so a controller could advertise a new version while pointing at an older official artifact — +/// bypassing the guard and recording a false installed version (finding: version not bound to the +/// release). We require the version encoded in the asset filename and the release tag embedded in +/// the download URL to agree with the release version before any bytes are fetched. +fn bind_artifact_version(app: &CraftApp, release: &Release, asset: &Asset) -> Result<(), String> { + let Some(release_version) = release.version.as_ref() else { return Ok(()) }; + let mismatch = || format!("{}'s download does not match the advertised version {}.", app.name, release.version_label()); + + // The version in the asset filename (`---.`), when it carries one. + let stems: Vec<&str> = app.stems().collect(); + if let Some(parsed) = artcraft_launcher_core::platform::parse_asset_name(&asset.name, &stems) + && version::parse(&parsed.version).as_ref() != Some(release_version) + { + return Err(mismatch()); + } + + // The release tag embedded in a GitHub download URL (`.../releases/download//`). + if let Some(tag) = asset.url.split("/releases/download/").nth(1).and_then(|rest| rest.split('/').next()) + && !tag.is_empty() + && version::parse(tag).is_some() + && version::parse(tag).as_ref() != Some(release_version) + && tag != release.tag + { + return Err(mismatch()); + } + Ok(()) +} + /// What a new install would write over: something already at its destination that the launcher /// didn't put there. pub fn occupied( @@ -2255,6 +2288,37 @@ mod tests { assert!(result.unwrap_err().contains("installed version 0.5.0 is newer")); } + #[test] + fn install_rejects_an_artifact_whose_version_is_not_the_advertised_one() { + // The release advertises 99.0.0, but the selected artifact is an older official build + // (filename and URL tag say 0.4.0). The guard must refuse before any download. + let dir = tempfile::tempdir().unwrap(); + let paths = Paths::under(dir.path()); + let http = Http::new().unwrap(); + let phase = &mut |_| (); + let locations = InstallLocations::default(); + let app = CraftApp::by_id("photocraft").unwrap(); + let release = Release { version: version::parse("99.0.0"), tag: "v99.0.0".into(), ..Release::default() }; + let asset = Asset { + name: "photocraft-0.4.0-linux-x86_64.AppImage".into(), + url: "https://github.com/storytold/photocraft/releases/download/v0.4.0/photocraft-0.4.0-linux-x86_64.AppImage".into(), + ..Asset::default() + }; + let stop = Stop::default(); + let mut job = Job { http: &http, paths: &paths, stop: &stop, phase, install_locations: &locations, replace: false }; + let result = install_at(app, &release, &asset, PackageKind::AppImage, None, None, &mut job, None); + assert!(result.is_err(), "mismatched artifact version must be rejected"); + assert!(result.unwrap_err().contains("does not match the advertised version")); + + // A matching artifact passes the guard (it fails later for unrelated reasons, not the bind). + let good = Asset { + name: "photocraft-99.0.0-linux-x86_64.AppImage".into(), + url: "https://github.com/storytold/photocraft/releases/download/v99.0.0/photocraft-99.0.0-linux-x86_64.AppImage".into(), + ..Asset::default() + }; + assert!(bind_artifact_version(app, &release, &good).is_ok()); + } + #[cfg(target_os = "linux")] #[test] fn package_kinds_order_matches_launcher_format() { From 1ef6b1a53ef7aa47476156b0c2d6dfad426b81d0 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 18:29:19 -0400 Subject: [PATCH 5/7] 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 jiff'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. --- AGENTS.md | 5 ++++- Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 316c267d..09a33281 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -114,7 +114,10 @@ only; English where there is none): never bundle a CJK font, they are 10 MB and 5. When fetching anything, use a generic `ArtCraft-Launcher/` User-Agent and never put a person's name, email or other personal details in requests. 6. **Time goes through `jiff`** (workspace dependency). Never hand-roll UTC/calendar conversion - (days-to-date algorithms, leap-year math); a module owns only its output format string. + (days-to-date algorithms, leap-year math); a module owns only its output format string. The one + exception is range extension: past the years jiff can represent, shift the date by whole 400-year + Gregorian cycles (146,097 days, after which the calendar repeats), let jiff compute the month, + day and time, and add the cycles back to the year. ## 3. Before you finish a task diff --git a/Cargo.toml b/Cargo.toml index 805f2a7c..96b38cd3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" semver = { version = "1", features = ["serde"] } log = "0.4" -# All date/time conversion goes through jiff (no hand-rolled calendar code; AGENTS.md). +# All date/time conversion goes through jiff (no hand-rolled calendar code beyond the 400-year range extension; AGENTS.md). jiff = "0.2" [profile.dev.package."*"] From 12b5064631f87287373776224e43a36a05330092 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 19:07:04 -0400 Subject: [PATCH 6/7] 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. --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 09a33281..e1d78929 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -116,8 +116,9 @@ only; English where there is none): never bundle a CJK font, they are 10 MB and 6. **Time goes through `jiff`** (workspace dependency). Never hand-roll UTC/calendar conversion (days-to-date algorithms, leap-year math); a module owns only its output format string. The one exception is range extension: past the years jiff can represent, shift the date by whole 400-year - Gregorian cycles (146,097 days, after which the calendar repeats), let jiff compute the month, - day and time, and add the cycles back to the year. + Gregorian cycles (146,097 days, after which the calendar repeats), let jiff compute the month and + day, and add the cycles back to the year (splitting seconds into hours, minutes and seconds is + plain arithmetic). ## 3. Before you finish a task From af4270fb6da8762a538cda4ea1aa6e831630f3a2 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 21 Oct 2026 18:19:55 -0400 Subject: [PATCH 7/7] security: reject shell metacharacters in opened web links Feed notice links and release-note hyperlinks are forwarded to the system opener when clicked. The pinned webbrowser crate's WSL fallback passes the URL to cmd.exe /c start while escaping only ^ and &, so a pipe (or other metacharacter) in an otherwise valid https URL becomes a command separator and runs a Windows command (CWE-78). Rather than depend on the third-party opener to neutralise the URL, refuse any link containing a shell/cmd metacharacter at the validation boundary, where a real https web link never needs one: - release::safe_web_link (release notes) now rejects shell metacharacters via the shared release::is_shell_meta, on top of the existing scheme/host/whitespace checks. - The feed notice link filter routes through the same rule and also rejects control characters. Addresses finding: widgets.rs/webbrowser WSL fallback CWE-78. --- crates/core/src/feed.rs | 16 +++++++++++----- crates/core/src/release.rs | 31 +++++++++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/crates/core/src/feed.rs b/crates/core/src/feed.rs index 4d24d8f2..5b14c796 100644 --- a/crates/core/src/feed.rs +++ b/crates/core/src/feed.rs @@ -407,9 +407,13 @@ impl RawNotice { if self.title.trim().is_empty() && self.body.trim().is_empty() { return None; } - let link = self - .maybe_web_link - .filter(|l| (l.starts_with("https://") || l.starts_with("http://")) && l.len() <= 2000 && !l.chars().any(char::is_whitespace)); + // The link may reach the system opener (whose WSL fallback shells out), so refuse any + // shell/cmd metacharacter or control character in it as well as whitespace (CWE-78). + let link = self.maybe_web_link.filter(|l| { + (l.starts_with("https://") || l.starts_with("http://")) + && l.len() <= 2000 + && !l.chars().any(|c| c.is_whitespace() || c.is_control() || release::is_shell_meta(c)) + }); Some(Notice { id: format!("{kind}:{}:{}", self.created_at.as_deref().unwrap_or(""), self.title.trim()), title: truncate(self.title.trim(), 200), @@ -612,7 +616,8 @@ mod tests { "\"alerts\": []", r#""alerts": [ {"title": "Security update", "body": "Update PdfCraft now.", "maybe_web_link": "https://getartcraft.com/security", "created_at": null}, - {"title": "Bad link", "body": "x", "maybe_web_link": "javascript:alert(1)"}]"#, + {"title": "Bad link", "body": "x", "maybe_web_link": "javascript:alert(1)"}, + {"title": "Shell link", "body": "x", "maybe_web_link": "https://getartcraft.com/a|calc.exe"}]"#, ) .replace( "\"app_renames\": []", @@ -620,9 +625,10 @@ mod tests { "new_name_lower": "docucraft", "description": "Same app, new name.", "renamed_at": "2026-10-09T08:00:00Z"}]"#, ); let feed = Feed::parse(&with_notices).unwrap(); - assert_eq!(feed.alerts.len(), 2); + assert_eq!(feed.alerts.len(), 3); assert_eq!(feed.alerts[0].link.as_deref(), Some("https://getartcraft.com/security")); assert_eq!(feed.alerts[1].link, None, "only web links are kept"); + assert_eq!(feed.alerts[2].link, None, "a link with shell metacharacters is dropped"); let titles: Vec<&str> = feed.announcements.iter().map(|n| n.title.as_str()).collect(); assert_eq!(titles, ["New: CADCraft 1.0", "PdfCraft is now DocuCraft"]); // Ids are stable across parses, so dismissals stick. diff --git a/crates/core/src/release.rs b/crates/core/src/release.rs index f975d176..6197b968 100644 --- a/crates/core/src/release.rs +++ b/crates/core/src/release.rs @@ -61,11 +61,28 @@ fn is_hex64(s: &str) -> bool { } /// Whether `url` is safe to hand to the system browser from untrusted text (release notes): -/// `https` only, a host, no user-info, no spaces or control characters. +/// `https` only, a host, no user-info, no spaces or control characters, and no shell metacharacters. +/// +/// The system opener is not always a direct `open`: the pinned `webbrowser` crate's WSL fallback +/// passes the URL to `cmd.exe /c start` while escaping only `^` and `&`, so a character like `|` +/// in an otherwise valid URL becomes a command separator (CWE-78). Because a legitimate +/// `https://` web link never needs these characters unescaped, we refuse any URL that contains a +/// shell/cmd metacharacter rather than rely on the opener to neutralise it. pub fn safe_web_link(url: &str) -> bool { let Some(rest) = url.strip_prefix("https://") else { return false }; let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); - url.len() <= 2000 && !authority.is_empty() && !authority.contains(['@', '\\']) && !url.chars().any(|c| c.is_control() || c.is_whitespace()) + url.len() <= 2000 + && !authority.is_empty() + && !authority.contains(['@', '\\']) + && !url.chars().any(|c| c.is_control() || c.is_whitespace()) + && !url.chars().any(is_shell_meta) +} + +/// Characters a command interpreter (POSIX shells or `cmd.exe`) may treat specially. A real +/// `https` URL never needs any of them unescaped in a browser-opened link. `%` matters because +/// `cmd.exe` expands `%NAME%` references, and an expanded value could itself carry metacharacters. +pub fn is_shell_meta(c: char) -> bool { + matches!(c, '|' | '&' | ';' | '<' | '>' | '(' | ')' | '$' | '`' | '"' | '\'' | '^' | '!' | '*' | '%' | '{' | '}' | '[' | ']') } /// The prefix every download of `repo` must start with. @@ -216,6 +233,16 @@ mod tests { "https://example.com/a b", "https://example.com/\nx", "https:///path", + // Shell/cmd metacharacters: the WSL opener fallback shells out, so these must be + // refused even inside an otherwise valid https URL (CWE-78). + "https://example.com/a|calc", + "https://example.com/p?x=1&y=2", + "https://example.com/`id`", + "https://example.com/$(whoami)", + "https://example.com/a;b", + "https://example.com/a>b", + "https://example.com/%COMSPEC%", + "https://example.com/%PATH%", ] { assert!(!safe_web_link(bad), "{bad:?}"); }