From bcd463101208a802f7834443028d61b3217c2aea Mon Sep 17 00:00:00 2001 From: maziggy Date: Wed, 3 Jun 2026 14:16:42 +0200 Subject: [PATCH] Bumped version --- CHANGELOG.md | 6 +++--- backend/app/core/config.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dced64eee..d563aea4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to Bambuddy will be documented in this file. -## [0.2.5b1] - Unreleased +## [0.2.4.5] - 2026-06-03 ### Added - **System theme detection — sidebar toggle and Settings selector follow OS dark/light preference (#1418, contributed by @TempleClause via PR #1501)** — `ThemeMode` gains a third value `'system'` alongside the existing `'dark'` / `'light'`. The provider listens to `window.matchMedia('(prefers-color-scheme: dark)')`, tracks the OS preference in real time, and exposes a new `resolvedMode: 'light' | 'dark'` to consumers — the actual rendered theme after resolving system → OS preference. Layout's sidebar toggle now cycles `dark → light → system → dark` with the icon hinting at the next stop (`Sun`→`Monitor`→`Moon`); the existing logo selection and the dark/light "active" panel highlight in Settings switched from `mode` to `resolvedMode` so they always reflect what's actually painted, regardless of whether the user chose explicitly or inherited from the OS. Settings → Appearance gained a 3-button Dark / Light / System selector (border-green-keys-off-`mode` so System actually highlights System even when it resolves to dark), with a "Settings saved" toast on click matching the adjacent Background/Accent/Style selects. Existing users' persisted `theme-mode` is untouched — anyone on `dark` or `light` stays there and simply gains an extra stop in the cycle; new installs default to `dark`. **Review-caught fixes shipped in the same PR**: (a) the project's `__tests__/setup.ts` mocked `window.matchMedia` with `vi.fn().mockImplementation(...)`, which `vi.restoreAllMocks()` in three test files reset to "return undefined" — pre-PR nothing called `matchMedia` at render time so the wipe went unnoticed, this PR was the first caller and broke 23 existing tests. Rewritten as a plain function (`Object.defineProperty(window, 'matchMedia', { writable: true, value: (query) => ({...}) })`) so `restoreAllMocks` can't touch it. (b) `themeToggleHint` had previously only been updated in `en.ts`; real translations now ship in all 8 non-English locales (de/es/fr/it/ja/pt-BR/zh-CN/zh-TW) describing the 3-state cycle without referencing the old sun/moon icon pair. (c) PR description reworded to honestly call out the sidebar cycle change as a behaviour change for every user of the toggle (`dark → light → system` now intercepts where users previously got `dark → light → dark`), with the persisted-preference-unchanged caveat made explicit. (d) New i18n key `nav.switchToSystem` with real translations across all 9 locales (`'Switch to system mode'` / `'Zum Systemmodus wechseln'` / `'システムモードに切替'` etc.). **Tests**: 11 new in `ThemeContext.test.tsx` (systemPreference inits from `matchMedia.matches`, change event updates state, resolvedMode follows explicit mode vs systemPreference per `mode` value, dark class applied based on resolved mode, `toggleMode` cycles dark→light→system→dark); 1 new in `Layout.test.tsx` (toggle button title attribute walks the cycle); 4 new in `SettingsPage.test.tsx` (all three buttons render, active green border keys off `mode`, click switches mode, click fires toast). 26 previously-broken tests in `AddNotificationModal.test.tsx` + `NotificationProviderCardStockAlerts.test.tsx` + `CameraTokensPage.test.tsx` pass again post-`setup.ts` fix. Frontend build clean (2682 modules); i18n parity green at 4995 keys × 9 locales (+1 from `switchToSystem`). Contributor handled the entire round-1 review (matchMedia mock, locale parity, PR honesty, full test coverage, toast parity, `.map()` refactor for the button group) in a single revision push, no follow-ups deferred. @@ -31,9 +31,9 @@ All notable changes to Bambuddy will be documented in this file. - **VP MQTT brute-force rate-limit per source IP** — 5 failed CONNECT attempts within a 60 s sliding window block further auth attempts from that IP for the rest of the window. Auto-recovers — no manual unblock. Constants `_AUTH_RATE_LIMIT_MAX_ATTEMPTS = 5` / `_AUTH_RATE_LIMIT_WINDOW_SECONDS = 60.0` are module-level for ops tunability. See Added section for full description. - **VP `access_code` no longer leaked in DEBUG logs** — Pre-fix: `PUT /virtual-printers/{id}` logged `body.model_dump(exclude_unset=True)` at DEBUG, which dumped the plaintext access code whenever the user saved a new one. Now the field is redacted (`***`) before the log emission. Violation surfaced by no-secrets-in-logs audit; not exploitable in the field (DEBUG is off by default) but is exactly the kind of leak the rule exists to prevent. - **VP FTP upload capped at 4 GiB (DoS guard)** — `cmd_STOR` now rejects an upload that crosses `MAX_UPLOAD_BYTES = 4 GiB`, deletes the partial file, and replies 426. Without the cap a runaway or malicious client could drive RSS or disk to exhaustion; 4 GiB is well above any realistic multi-plate `.gcode.3mf`. Same code path adds the streaming rewrite (see Changed section for details). - -### Security - **Path-traversal hardening across the upload / import / file-write surface (routes + services); fifth CI backstop ships alongside** — A private path-traversal report against `POST /api/v1/projects/import/file` traced two attacker-controlled strings being joined to `library_dir` with no resolve + containment check: (a) `linked_folders[*].name` from the request's `project.json` ("Vector A" — an absolute path in this field collapsed `library_dir / "/anywhere"` to `Path("/anywhere")` because pathlib discards the left side when the right is absolute, letting the next `write_bytes` land anywhere the backend could write), and (b) per-entry `zf.namelist()` paths from the ZIP itself ("Vector B" — ZIP filenames carry `..` segments by spec and the join `library_dir / folder_name / relative_path` had no per-component check). Concrete escalation: drop a `.pth` file into the venv's `site-packages` directory for code execution on next service restart; overwrite the JWT signing-secret file to forge an admin token; overwrite `~/.ssh/authorized_keys` or `~/.bashrc` on native installs. **Fix is structural, not just patch the diff** (per [[feedback_dont_dismiss_preexisting]]). New `backend/app/utils/safe_path.py::safe_join_under(parent, *parts)` helper joins under a trusted parent, resolves both sides, asserts `is_relative_to(parent.resolve())`, and rejects up-front empty / null-byte / absolute path components. Wired into `import_project_file` at both vectors. **Adjacent fix from the routes audit**: `GET /api/v1/archives/{id}/photos/{filename}` had NO validation on `filename` and FileResponse-served arbitrary paths — the existing DELETE endpoint at least had a membership check against `archive.photos` (which is UUID-generated on upload), but GET shared neither the check nor any traversal guard. Both GET and DELETE now route through `safe_join_under` for defence-in-depth on top of the membership check. **Second adjacent fix from the services audit**: `ArchiveService.attach_timelapse(archive_id, data, filename)` in `backend/app/services/archive.py:1456` wrote `archive_dir / filename` where `filename` ultimately comes from either a printer's FTP listing (compromised-printer threat model — the printer is part of the trust surface) or the `?filename=...` query param on `POST /api/v1/archives/{id}/timelapse/select`. A malicious printer that returns a directory listing entry with `..` segments could write the timelapse bytes outside the archive directory; the `f.get("name") == filename` gate in the route did not prevent it because the gate is satisfied by whatever the printer claims is on disk. `attach_timelapse` now routes through `safe_join_under(..., http=False)` and returns `False` (logging the rejection) when the join would escape — matching the existing not-found contract of the function rather than raising 400 from inside a background task. **Audit sweep methodology**: AST-walked every Python file under `backend/app/api/routes/` AND `backend/app/services/` for `Path / Name` shapes (the exact shape that produced the original report). 25 additional route-layer sites and 8 additional service-layer sites confirmed safe case-by-case (UUID-generated filenames written by Bambuddy itself, `_safe_filename(...)` / `Path(arg).name` basename-stripped inputs, `os.walk`-discovered names, denylist + format-validated backup names, hardcoded constants iterated through a tuple, DB-stored paths whose write origin already goes through a resolved-and-containment-checked helper). Each safe site got a `# SEC-PATH-OK: ` marker so future audits can trust the inline guard at a glance. Six pre-existing safe-with-marker sites (`library.py` external upload, `archives.py` timelapse output, `projects.py` attachment download/delete, `settings.py` backup extractall) carry the same marker shape. **Fifth CI backstop** `test_route_path_arithmetic_is_safe_joined_or_marked` (`backend/tests/unit/test_no_unsafe_path_joins.py`) AST-walks every Python file in `backend/app/api/routes/` AND `backend/app/services/` and fails the build on any ` / ` join that doesn't either route through `safe_join_under` or carry the marker on the join line. Joins matching the higher-structure shapes (Attribute access, Subscript, f-string, `str(...)` call) are categorically different and out of scope — those are caught by the broader audit sweep, not the regression backstop. The services layer is in scope because it receives values from the routes verbatim AND from external sources Bambuddy has no control over (the printer FTP-listing case above). **Tests**: 17 unit tests for `safe_join_under` covering every escape vector (absolute path, Windows abs path, `..` segments, embedded `..`, null byte, empty string, no parts, non-str, plus legitimate nested-path round-trip); 4 integration tests against `POST /api/v1/projects/import/file` exercising the full FastAPI stack with the verbatim shape from the report (absolute path in `folder_name` → 400 + filesystem assertion that the target file doesn't exist; `..` in `folder_name` → 400; `..` in `relative_path` → 400; legitimate nested ZIP still imports cleanly to guard against the fix being over-strict); 3 unit tests against `ArchiveService.attach_timelapse` exercising the compromised-printer threat model (filename with `..` segments → returns False + no file at the escape target; absolute filename → returns False + no file at `/tmp`; legitimate `timelapse_YYYY-MM-DD_HH-MM-SS.mp4` → returns True + file lands inside archive_dir, guarding against the fix being over-strict). **SECURITY.md** gains a fifth rule + a fifth row in the CI-test mapping table; the rule explicitly names the printer FTP-listing case as in-scope to set the expectation for future services-layer audits. Full 5500+ test backend suite green; ruff clean. + + ### Fixed - **Print-run log, spool usage history, camera-token list, and SpoolBuddy device "last calibrated" timestamps now render in the browser's local timezone instead of UTC (#1602, reported by @maziggy and confirmed by @IndividualGhost1905 with a UTC+3 reproduction)** — Reporter saw print-run completion timestamps show UTC clock values (e.g. `07:50` instead of the correct local `10:50` for Berlin / `10:50` instead of `13:50` for a UTC+3 host). Same shape as the #504 timezone-offset bug from Feb 2026 — frontend display helpers calling `new Date(isoString)` directly on backend timestamps without timezone indicators. Per ECMAScript, a bare `"2026-06-02T07:50:00"` is parsed as **local time**, so a UTC-stored value gets displayed as if its numeric components were already local — visually identical to UTC. The #504 fix patched 13 sites but missed four: PrintLogTable and SpoolUsageHistory hadn't been written yet; CameraTokensPage and SpoolBuddySettingsPage existed but were overlooked. **Fix** — replaced the bare `new Date(iso)` calls in `frontend/src/components/PrintLogTable.tsx::formatDate` (per-archive Runs list — the reporter's literal symptom), `frontend/src/components/SpoolUsageHistory.tsx::formatDate` (spool usage records), `frontend/src/pages/CameraTokensPage.tsx::formatDate` + `isExpired` (long-lived camera token created / expires / last-used columns), and `frontend/src/pages/spoolbuddy/SpoolBuddySettingsPage.tsx::formatDateTime` (SpoolBuddy device "last calibrated") with calls to the shared `parseUTCDate()` helper from `utils/date.ts`, which appends `Z` to naive ISO strings and parses TZ-tagged strings as-is — already used by every other date formatter in the codebase and well-tested (`parseUTCDate` has 4 dedicated test cases covering null/empty/tagged/naive inputs). `isExpired` in `CameraTokensPage.tsx` got the same treatment because comparing a misparsed Date against `Date.now()` would have produced false "not expired" / "expired" results around the TZ-offset boundary. **What this does NOT fix** — the printer-card ETA reporter #1 described (10:50 + 57m showing 09:48). That comes from `formatETA(status.remaining_time)` which is purely client-side (`new Date()` plus minutes from the WebSocket payload, then `toLocaleTimeString([])`); for it to render UTC the browser timezone itself would need to be UTC. That's a browser / OS config issue, not Bambuddy's display. If reporter #1 was actually looking at log timestamps (the same surface reporter #2 explicitly called out), this fix covers it; otherwise their ETA complaint stays a config matter. **Audit confirmed no other regressions** — grepped every `new Date(` call in `frontend/src/` for backend-supplied string arguments. Remaining call sites either pass a number (epoch ms from chart data — `AMSHistoryModal.tsx:327,349`), construct from a numeric date string only with no time component (chart axis labels — `FilamentTrends.tsx:57,129`), use the result only for `.getTime()` arithmetic where the same TZ offset cancels out (sort comparators in `StatsPage.tsx:920`, `ForecastPanel.tsx:101,111,112,141`, `FilamentTrends.tsx:70`), or already wrap in `parseUTCDate(...) || new Date(...)` as defensive fallback (`StatsPage.tsx:607,895`). `FailureDetectionSettings.tsx:359` uses `new Date(ev.timestamp)` directly but the backend (`obico_detection.py:293`) emits `datetime.now(timezone.utc).isoformat()` which includes a `+00:00` indicator so ECMAScript parses it as UTC correctly — unchanged. **No new tests added** — the four `formatDate` / `formatDateTime` helpers are local to their files and the bug is mechanical "use the existing helper"; `parseUTCDate` itself has full coverage in `__tests__/utils/date.test.ts`. Frontend build clean, ESLint zero output, full date-utils + impacted-component vitest suites (103 tests) green, i18n parity green at 5007 leaves × 9 locales. - **Archive card's Print Time + accuracy badge are now consistent for multi-run / multi-plate archives (#1608, reported via an AI-assisted diagnosis that included the failing SQL, file line numbers, and a worked example for archive #65)** — Reporter's case: 3-plate `.gcode.3mf` printed plate-by-plate over 9 runs. Card showed `1h 46m +188%` next to the now-correct `156.7g` / `$9.81`. The 1h 46m = 6364 s = one run's `completed_at − started_at`; the +188% = `print_time_seconds / 6364` − 100 % where `print_time_seconds` is 18354 s (the whole-file estimate the #1593 parser fix correctly stores). The two halves describe different scopes — apples-to-oranges. **Root cause** — `backend/app/api/routes/archives.py::compute_time_accuracy` (line 152) only inspects the archive row's own `started_at` / `completed_at`, which reflect the latest run, while `archive.print_time_seconds` is the sum across plates post-#1593. The existing 5-500 % sanity band catches truly broken values but lets the deterministic N×100% shape through (300% for a 3-plate file). `archive_to_response` calls `compute_time_accuracy` on every list / detail / search / project-archive / patch render (line 275), so the bad number reaches the frontend on every card surface. The stats endpoint (`/api/v1/archives/stats`, line 940-988) has its OWN per-run accuracy loop with a tighter 50-200 % band filter shipped with #1593 — that's untouched and stays correct. **Fix** — `compute_time_accuracy(archive, run_aggregate=None)` gains an optional `run_aggregate` argument. When `run_aggregate["run_count"] > 1`, both `actual_time_seconds` and `time_accuracy` are returned as `None`. The frontend already falls through to `archive.print_time_seconds` for the Time display (`archive.actual_time_seconds || archive.print_time_seconds`) and conditionally renders the badge only when `archive.time_accuracy` is truthy, so multi-run archives now show "Estimated 5h 6m" with no badge instead of "Actual 1h 46m +188%". Single-run archives — the case the badge was designed for, and the only case where one-run actual versus whole-file estimate is a meaningful ratio — keep the original behaviour verbatim. **Audit-wide** — `archive_to_response` now passes `run_aggregate` through to `compute_time_accuracy` at the response-conversion call site. The 3 endpoints that did NOT previously load run aggregates (`backend/app/api/routes/archives.py` search endpoint's pre-FTS fast path at line 583 and FTS path at line 610, the single-archive PATCH endpoint at line 1419, and `backend/app/api/routes/projects.py::list_project_archives` at line 706) now batch-load `_load_run_aggregates` and pass it through, so the badge-suppression applies on every card surface — not just the main list and detail endpoints. One extra `SELECT … GROUP BY archive_id` per endpoint (the helper is already batched), cheap. Per the [[feedback_pr_reviews_thorough]] HARD RULE the fix is shipped across every call site that renders an archive card. **What this does NOT change** — the stats endpoint's per-run accuracy aggregation at line 940-988, its 50-200% band filter, the `archive.started_at` / `completed_at` source-of-truth for the latest-run timestamps, the frontend `ArchivesPage.tsx:1004-1022` rendering logic, or the time-accuracy computation for single-run archives. Reprint scope is unchanged (the reporter's option A — comparing summed run durations against the whole-file estimate — was not pursued because it produces a different but equally misleading number for the reprints-of-a-single-plate-file shape, where sum-of-runs = N × estimate). **Tests** — `backend/tests/unit/test_archive_run_aggregation.py::TestComputeTimeAccuracyMultiRun`: 4 new direct unit tests for the function — single-run archive keeps original badge, no `run_aggregate` argument keeps original badge (defends the legacy caller pattern), multi-run archive (reporter's exact 9-run case) clears both fields, and `run_count: 0` edge case keeps original behaviour. Two new integration tests against the live archives list endpoint: `test_archive_list_suppresses_time_accuracy_for_multi_run_archives` is the #1608 regression (3-plate plate-by-plate fixture, asserts both `actual_time_seconds is None` and `time_accuracy is None` AND that the estimate `print_time_seconds` survives so the card has something to render), and `test_archive_list_keeps_time_accuracy_for_single_run_archives` is the sanity check that the badge still shows for the happy path. Full backend pytest 3680 passed under `-n 30`; ruff clean. **No frontend change required** — the existing rendering logic in `ArchivesPage.tsx:1004-1026` (`formatDuration(archive.actual_time_seconds || archive.print_time_seconds || 0)` for the time + `{archive.time_accuracy && …}` conditional badge) naturally produces the desired "show estimate, no badge" presentation when the backend returns null for both fields. diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 2fab2f3dc..7e4b9232e 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -6,7 +6,7 @@ from pathlib import Path from pydantic_settings import BaseSettings # Application version - single source of truth -APP_VERSION = "0.2.5b1" +APP_VERSION = "0.2.4.5" GITHUB_REPO = "maziggy/bambuddy" BUG_REPORT_RELAY_URL = os.environ.get("BUG_REPORT_RELAY_URL", "https://bambuddy.cool/api/bug-report")