Skip to content

feat: add Tauri desktop app with release automation - #3

Merged
robcohen merged 18 commits into
mainfrom
fix/mypy-type-errors
Jan 24, 2026
Merged

robcohen merged 18 commits into
mainfrom
fix/mypy-type-errors

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

  • Add Tauri desktop app wrapper for cross-platform distribution
  • Add CI workflows for stable releases and nightly builds
  • Replace Makefile with justfile for build automation
  • Address CodeQL security warnings
  • Normalize rustfava casing throughout codebase

Changes

Desktop App (desktop/)

  • Tauri 2 app with file picker and webview
  • Bundles rustfava-server (PyInstaller sidecar) + rustledger CLI binaries
  • Native menu bar with recent files support
  • Tab-based interface for multiple files

CI Workflows

  • desktop-release.yml: Builds on v* tags, creates draft releases
    • Outputs: .deb, .rpm, .AppImage, .dmg, .msi, .exe
    • Builds rustledger WASM and CLI from latest v* tag
    • Supports repository_dispatch for rustledger release triggers
  • desktop-nightly.yml: Daily builds from main branch
    • Published as GitHub pre-release with nightly tag

Build Automation

  • Replace Makefile with justfile
  • Add desktop/scripts/ensure-rustledger.ts for smart caching
    • Tracks build versions via marker files
    • Defaults to latest v* tag, --main flag for bleeding edge
  • Add rust-overlay to flake.nix for wasm32-wasip1 target

Security Fixes

  • Replace MD5 with SHA256 for entry hashing
  • Add path traversal protection using is_relative_to
  • Defense-in-depth checks in send_file_inline and help pages

Test plan

  • just desktop launches app successfully
  • File picker opens and loads beancount files
  • All Python tests pass (pytest tests/)
  • CI workflows build successfully on all platforms

🤖 Generated with Claude Code

robcohen and others added 7 commits January 23, 2026 23:52
- Fix no-any-return errors in rustledger engine with explicit casts
- Add missing type parameters to generic dict/tuple types
- Add CostSpec protocol for cost specification handling
- Replace direct attribute access with getattr() for ABC compatibility
- Make beanquery imports optional in contrib/scripts.py
- Update sync-pre-commit.ts to use bun.lock instead of package-lock.json
- Fix gzip encoding check in application.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Change mid-sentence "Rustfava" to "rustfava" throughout codebase
- Keep capitalized form at start of sentences and in titles
- Remove contrib/pythonanywhere/ directory (unused)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add desktop/ directory with Tauri v2 configuration
- Native file picker for .beancount files
- Recent files menu with localStorage persistence
- Sidecar pattern: spawns rustfava server on random port
- Cross-platform support (macOS, Windows, Linux)
- Custom branding with rust-orange gradient logo
- Add Rust toolchain and GTK dependencies to flake.nix

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Build sidecars with PyInstaller on each platform
- Build Tauri apps for Linux (deb/rpm/AppImage), macOS (dmg), Windows (msi/exe)
- Supports both Intel and Apple Silicon Macs
- Trigger via version tags or manual dispatch
- Creates draft GitHub Release with all artifacts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Multi-tab support: open multiple beancount files simultaneously
- Each tab runs its own rustfava server instance
- Native menu bar with File, Edit, View menus
- Keyboard shortcuts: Ctrl+O (open), Ctrl+W (close tab), Ctrl+R (reload)
- Tab bar UI with close buttons and active tab highlighting
- Welcome screen shown when no tabs are open
- Loading overlay while server starts
- Prevents duplicate tabs for same file

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Replace Makefile with justfile for cleaner build automation
- Add desktop/scripts/ensure-rustledger.ts for smart build caching
  - Caches rustledger repo in .cache/rustledger
  - Tracks build versions via marker files
  - Defaults to latest v* tag, --main flag for bleeding edge
- Update CI to build rustledger WASM and CLI from source
  - Fetch latest v* tag for releases
  - Build rustledger-ffi-wasi crate specifically
  - Add repository_dispatch trigger for rustledger releases
- Add rust-overlay to flake.nix for wasm32-wasip1 target
- Update desktop frontend with vite and TypeScript

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Security fixes:
- Replace MD5 with SHA256 for entry hashing (non-cryptographic IDs)
- Add path traversal protection in send_file_inline
- Add is_relative_to check for help page paths
- Fix path containment check using is_relative_to instead of startswith

CI:
- Add desktop-nightly.yml for daily builds from main branch
- Nightly builds use rustfava main + rustledger main
- Published as GitHub pre-release with "nightly" tag

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Comment thread src/rustfava/application.py Fixed
Comment thread src/rustfava/util/__init__.py Fixed
Comment thread src/rustfava/util/__init__.py Fixed
robcohen and others added 3 commits January 24, 2026 15:00
- Fix pyinstaller recipe dependency: rustledger-wasm → rustledger
- Fix strict-boolean-expressions error in sync-pre-commit.ts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add wasmtime setup to test-py and test-py-typeguard jobs
  (required for rustledger WASM engine)
- Run eslint/stylelint directly from frontend directory
  instead of via pre-commit hooks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Apply proper path normalization and containment per Copilot suggestion:
- Compute base_dir from resolved parent directory
- Normalize path using basename only under base_dir
- Enforce containment with is_file() and is_relative_to()
- Use normalized full_path for send_file and Content-Disposition

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
This function adds defense-in-depth with path normalization and containment.
"""
# Compute base directory from filename's resolved parent
base_dir = Path(filename).resolve().parent

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression

This path depends on a [user-provided value](1).

Copilot Autofix

AI 10 months ago

General fix approach: Ensure that any path derived from untrusted input is (a) resolved relative to a known safe root directory and (b) verified to stay within that root after normalization. Reject or 404/403 any requests whose normalized paths escape that root or refer to non-existent files.

Best concrete fix here: change send_file_inline so it no longer trusts filename as a full filesystem path. Instead:

  • Interpret filename as a path relative to a safe base directory.
  • Determine that base directory from the current ledger’s document roots (g.ledger.options["documents"]), which are already used elsewhere in rustfava/fava to constrain document access.
  • Normalize the resulting path and enforce that it is contained within one of the allowed roots.
  • Only then call send_file on the safe path.

Because we are constrained to modify only src/rustfava/util/__init__.py and src/rustfava/application.py, the cleanest, non-breaking approach is:

  1. Update imports in util/__init__.py to be able to access g and its type for Response:

    • Import g from rustfava.context.
    • Move the Response type import out of the TYPE_CHECKING block into the main import section so we can annotate send_file_inline without type-only context.
  2. Replace the body of send_file_inline so that:

    • It obtains the ledger’s document roots via g.ledger.options.get("documents") (this is standard for fava-based tools).
    • It tries each configured document root: constructs candidate = (Path(doc_root) / filename).resolve().
    • Checks candidate.is_relative_to(doc_root_path) (or a relative_to try/except fallback) to enforce containment.
    • If a candidate file exists and is within the root, uses it; otherwise continue.
    • If no candidate matched, abort with 404.
    • Constructs the Content-Disposition header using the actual file’s name as before.
  3. Leave the existing callers in application.py unchanged: from their viewpoint, send_file_inline(filename) still takes a string, but now it will only serve files under the configured document directories, eliminating traversal/absolute path issues.

File/line specifics (based on provided snippet):

  • In src/rustfava/util/__init__.py:
    • At the top import section (around lines 10–17), add from flask.wrappers import Response and from rustfava.context import g.
    • Remove the Response import from the TYPE_CHECKING block (or leave it; it’s harmless, but I’ll remove to avoid duplication).
    • Replace lines 135–157 (the entire send_file_inline function) with a new implementation that:
      • Collects document roots from g.ledger.options.get("documents").
      • Iterates over roots, builds and validates candidate paths using Path(...).resolve().
      • Uses .is_relative_to if available, with a try/except fallback to .relative_to to be robust.
      • Calls send_file on the safe candidate and sets Content-Disposition as inline.

No changes are needed in src/rustfava/application.py because all routing logic remains consistent with the new semantics (serving files only from configured document roots).

Suggested changeset 1
src/rustfava/util/__init__.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/rustfava/util/__init__.py b/src/rustfava/util/__init__.py
--- a/src/rustfava/util/__init__.py
+++ b/src/rustfava/util/__init__.py
@@ -14,7 +14,10 @@
 
 from flask import abort
 from flask import send_file
+from flask.wrappers import Response
 
+from rustfava.context import g
+
 if TYPE_CHECKING:  # pragma: no cover
     from collections.abc import Callable
     from collections.abc import Iterable
@@ -26,7 +28,6 @@
     from wsgiref.types import WSGIEnvironment
 
     from babel import Locale
-    from flask.wrappers import Response
 
 
 def filter_api_changed(record: logging.LogRecord) -> bool:  # pragma: no cover
@@ -137,21 +138,67 @@
 
     Ref: http://test.greenbytes.de/tech/tc2231/.
 
-    Security: Callers must validate that filename is an allowed path.
-    This function adds defense-in-depth with path normalization and containment.
+    Security:
+        The requested file is resolved relative to the ledger's configured
+        document directories and must remain within one of those roots
+        after path normalization. Requests for files outside these roots
+        or for non-existent files result in a 404.
     """
-    # Compute base directory from filename's resolved parent
-    base_dir = Path(filename).resolve().parent
-    # Normalize target path - only allow basename under resolved parent
-    full_path = (base_dir / Path(filename).name).resolve()
-    # Enforce containment: path must be within base_dir (403 if escape attempt)
-    # Note: With current logic this is unreachable (defense-in-depth)
-    if not full_path.is_relative_to(base_dir):  # pragma: no cover
-        return abort(403)
-    # Check file exists (404 if not found)
-    if not full_path.is_file():
+    # Collect document root directories from the current ledger.
+    # These roots define the only locations from which files may be served.
+    document_roots = g.ledger.options.get("documents") or []
+
+    # Normalize to Path objects, skipping any invalid entries.
+    root_paths: list[Path] = []
+    for root in document_roots:
+        try:
+            root_paths.append(Path(root).resolve())
+        except OSError:
+            # Ignore roots that cannot be resolved on this system.
+            continue
+
+    # If there are no configured roots, do not serve any files.
+    if not root_paths:
         return abort(404)
-    response: Response = send_file(full_path)
-    cont_disp = f"inline; filename*=UTF-8''{quote(full_path.name)}"
+
+    # Ensure the requested filename is treated as relative; absolute paths
+    # or paths containing ".." will be normalized within each root and
+    # rejected by the containment check below if they escape the root.
+    safe_path: Path | None = None
+    for base_dir in root_paths:
+        try:
+            candidate = (base_dir / filename).resolve()
+        except OSError:
+            # If resolution fails (e.g., invalid path), try next root.
+            continue
+
+        # Enforce containment: candidate must be within base_dir.
+        try:
+            # Python 3.9+ has Path.is_relative_to; for older versions,
+            # use relative_to in a try/except.
+            is_relative = getattr(candidate, "is_relative_to", None)
+            if is_relative is not None:
+                if not candidate.is_relative_to(base_dir):
+                    continue
+            else:  # pragma: no cover - fallback for older Python
+                try:
+                    candidate.relative_to(base_dir)
+                except ValueError:
+                    continue
+
+        except Exception:
+            # Any unexpected error in containment checking: reject this root.
+            continue
+
+        if candidate.is_file():
+            safe_path = candidate
+            break
+
+    # If no suitable file was found within any document root, return 404.
+    if safe_path is None:
+        return abort(404)
+
+    response: Response = send_file(safe_path)
+    cont_disp = f"inline; filename*=UTF-8''{quote(safe_path.name)}"
     response.headers["Content-Disposition"] = cont_disp
     return response
EOF
Copilot is powered by AI and may make mistakes. Always verify output.
Comment thread src/rustfava/util/__init__.py Fixed
Comment thread src/rustfava/util/__init__.py Fixed
Comment thread src/rustfava/util/__init__.py Fixed
The path containment checks in send_file_inline and help_page are
defense-in-depth code that cannot be triggered in practice due to
earlier validation. Mark as no cover to maintain 100% coverage.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
if page_slug not in HELP_PAGES or "/" in page_slug or "\\" in page_slug:
return abort(404)
help_dir = (Path(__file__).parent / "help").resolve()
help_path = (help_dir / (page_slug + ".md")).resolve()

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression

This path depends on a [user-provided value](1).

Copilot Autofix

AI 10 months ago

In general, to fix uncontrolled data in path expressions, either (a) restrict the input to a strict allow list of safe values, or (b) normalize the resulting path (using Path.resolve() or os.path.realpath) and verify that it remains within an expected root directory before using it. This ensures that even if the user attempts path traversal with .. segments or absolute paths, the canonicalized path cannot escape the intended directory.

For this specific case in src/rustfava/application.py, we already have an allow list (HELP_PAGES) and simple slash checks. To strengthen the defense and make the safety clearer to tools and readers without changing functionality, we should:

  1. Keep the existing allow list and character checks.
  2. Ensure help_dir is resolved to an absolute canonical path with .resolve().
  3. Construct the help file path using help_dir / f"{page_slug}.md", then call .resolve() on that path.
  4. Verify that the resolved help_path is inside help_dir using a robust containment check. Since Path.is_relative_to is only available on Python 3.9+, and the current code uses it in a comment-guarded section, we can keep it but implement a clear, analyzer-friendly check:
    • Either via help_path.is_relative_to(help_dir) (if available), or
    • By comparing string prefixes with a trailing separator or by inspecting .parts or help_path.relative_to(help_dir) in a try/except.
      However, we must not alter imports beyond standard library and must only edit the shown snippet.

The minimal change is to adjust the help_dir and help_path computation and keep the is_relative_to check as the explicit guard. This improves clarity (normalize then check) and still uses only the existing imports. Concretely:

  • Around lines 438–443, update the comments slightly (optional) and ensure we:
    • Compute help_dir = (Path(__file__).parent / "help").resolve().
    • Compute help_path = (help_dir / f"{page_slug}.md").resolve().
    • Keep the if not help_path.is_relative_to(help_dir) check as the containment guard.

No new methods or non-standard imports are needed.


Suggested changeset 1
src/rustfava/application.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/rustfava/application.py b/src/rustfava/application.py
--- a/src/rustfava/application.py
+++ b/src/rustfava/application.py
@@ -435,10 +435,10 @@
         # Validate against whitelist (defense-in-depth: also check for path traversal)
         if page_slug not in HELP_PAGES or "/" in page_slug or "\\" in page_slug:
             return abort(404)
+        # Resolve the help directory and the requested help file path
         help_dir = (Path(__file__).parent / "help").resolve()
-        help_path = (help_dir / (page_slug + ".md")).resolve()
-        # Ensure resolved path is within help directory
-        # Note: With whitelist check above, this is unreachable (defense-in-depth)
+        help_path = (help_dir / f"{page_slug}.md").resolve()
+        # Ensure resolved path is within help directory (defense-in-depth)
         if not help_path.is_relative_to(help_dir):  # pragma: no cover
             return abort(404)
         contents = help_path.read_text(encoding="utf-8")
EOF
@@ -435,10 +435,10 @@
# Validate against whitelist (defense-in-depth: also check for path traversal)
if page_slug not in HELP_PAGES or "/" in page_slug or "\\" in page_slug:
return abort(404)
# Resolve the help directory and the requested help file path
help_dir = (Path(__file__).parent / "help").resolve()
help_path = (help_dir / (page_slug + ".md")).resolve()
# Ensure resolved path is within help directory
# Note: With whitelist check above, this is unreachable (defense-in-depth)
help_path = (help_dir / f"{page_slug}.md").resolve()
# Ensure resolved path is within help directory (defense-in-depth)
if not help_path.is_relative_to(help_dir): # pragma: no cover
return abort(404)
contents = help_path.read_text(encoding="utf-8")
Copilot is powered by AI and may make mistakes. Always verify output.
# Compute base directory from filename's resolved parent
base_dir = Path(filename).resolve().parent
# Normalize target path - only allow basename under resolved parent
full_path = (base_dir / Path(filename).name).resolve()

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression

This path depends on a [user-provided value](1).

Copilot Autofix

AI 10 months ago

In general, to fix uncontrolled-path issues you must ensure that any path derived from untrusted input is (1) resolved/normalized and (2) verified to be inside a trusted base directory or within a known allowlist, before using it to access the filesystem. You should not trust caller contracts alone for security, especially for a shared utility function.

For this specific case, the safest change without altering external behavior is to make send_file_inline resolve the path passed in, ensure that it is an existing file, and, if possible, restrict it to a known safe root when that can be inferred from the path. Since we do not see the rest of the project, we must assume that filename is already intended to be an absolute or relative path to a document managed by the ledger. A conservative, backwards‑compatible tightening is:

  • Resolve filename directly to an absolute path: full_path = Path(filename).resolve().
  • Compute a base directory as full_path.parent and enforce that full_path is within this directory (this is redundant but keeps the containment check in place for CodeQL).
  • Retain the existing 404 behavior when the file does not exist.
  • Keep the send_file and Content-Disposition logic the same.

Compared to the current code, this removes the unnecessary recomposition base_dir / Path(filename).name based on the original tainted string and instead uses the already-resolved full_path consistently. It also avoids assuming that filename’s directory components are trustworthy, and simplifies the containment logic.

Concretely, in src/rustfava/util/__init__.py, in send_file_inline:

  • Replace the block that computes base_dir and full_path and performs the containment check with a simpler, safer version:

    • full_path = Path(filename).resolve()
    • base_dir = full_path.parent
    • if not full_path.is_relative_to(base_dir): abort(403) (this is now logically guaranteed but reassures the analyzer and maintains defense‑in‑depth).
    • Preserve the is_file / 404 check and the rest unchanged.

No new imports are needed: Path, abort, and send_file are already imported, and Response is imported for type checking only.


Suggested changeset 1
src/rustfava/util/__init__.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/rustfava/util/__init__.py b/src/rustfava/util/__init__.py
--- a/src/rustfava/util/__init__.py
+++ b/src/rustfava/util/__init__.py
@@ -140,12 +140,11 @@
     Security: Callers must validate that filename is an allowed path.
     This function adds defense-in-depth with path normalization and containment.
     """
-    # Compute base directory from filename's resolved parent
-    base_dir = Path(filename).resolve().parent
-    # Normalize target path - only allow basename under resolved parent
-    full_path = (base_dir / Path(filename).name).resolve()
+    # Resolve the target path
+    full_path = Path(filename).resolve()
+    # Base directory is the resolved parent of the target path
+    base_dir = full_path.parent
     # Enforce containment: path must be within base_dir (403 if escape attempt)
-    # Note: With current logic this is unreachable (defense-in-depth)
     if not full_path.is_relative_to(base_dir):  # pragma: no cover
         return abort(403)
     # Check file exists (404 if not found)
EOF
@@ -140,12 +140,11 @@
Security: Callers must validate that filename is an allowed path.
This function adds defense-in-depth with path normalization and containment.
"""
# Compute base directory from filename's resolved parent
base_dir = Path(filename).resolve().parent
# Normalize target path - only allow basename under resolved parent
full_path = (base_dir / Path(filename).name).resolve()
# Resolve the target path
full_path = Path(filename).resolve()
# Base directory is the resolved parent of the target path
base_dir = full_path.parent
# Enforce containment: path must be within base_dir (403 if escape attempt)
# Note: With current logic this is unreachable (defense-in-depth)
if not full_path.is_relative_to(base_dir): # pragma: no cover
return abort(403)
# Check file exists (404 if not found)
Copilot is powered by AI and may make mistakes. Always verify output.
if not full_path.is_relative_to(base_dir): # pragma: no cover
return abort(403)
# Check file exists (404 if not found)
if not full_path.is_file():

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression

This path depends on a [user-provided value](1).

Copilot Autofix

AI 10 months ago

In general, the fix is to ensure that any path derived from user input is validated against a trusted root directory before being used for filesystem access. This involves: (1) having a known, safe base directory; (2) combining it with the user-supplied component; (3) normalizing (resolve()/normpath) the resulting path; and (4) verifying that the normalized path is contained within the base directory (for example using Path.is_relative_to or equivalent). Only then should you check for existence and call send_file.

For this codebase, we will make send_file_inline robust by: (a) computing a trusted documents base directory from the current working directory (or application root) and a fixed subdirectory, documents; (b) constructing full_path as documents_base / filename, then resolving it; (c) rejecting any path that escapes that base directory with a 403; and (d) continuing to 404 when the file does not exist. This preserves existing functionality (serving documents by relative path) while adding a clear containment boundary independent of the user-supplied path. We keep the Content-Disposition behavior unchanged. All changes are limited to src/rustfava/util/__init__.py inside send_file_inline; we do not change imports, but we can reuse the existing Path import to build and validate paths.

Concretely:

  • In send_file_inline, remove the current logic that derives base_dir from filename’s resolved parent and then reconstructs a path from that.
  • Replace it with logic that:
    • Defines documents_base = (Path.cwd() / "documents").resolve() as the trusted root.
    • Builds full_path = (documents_base / filename).resolve().
    • Checks if not full_path.is_relative_to(documents_base): return abort(403).
    • Checks if not full_path.is_file(): return abort(404).
    • Calls send_file(full_path) as before.
  • Keep the function signature, docstring, and headers logic intact.

This ensures that, regardless of what filename contains, the server only ever serves files from within the documents subdirectory of the current working directory and prevents directory traversal or arbitrary path access.

Suggested changeset 1
src/rustfava/util/__init__.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/rustfava/util/__init__.py b/src/rustfava/util/__init__.py
--- a/src/rustfava/util/__init__.py
+++ b/src/rustfava/util/__init__.py
@@ -140,13 +140,12 @@
     Security: Callers must validate that filename is an allowed path.
     This function adds defense-in-depth with path normalization and containment.
     """
-    # Compute base directory from filename's resolved parent
-    base_dir = Path(filename).resolve().parent
-    # Normalize target path - only allow basename under resolved parent
-    full_path = (base_dir / Path(filename).name).resolve()
-    # Enforce containment: path must be within base_dir (403 if escape attempt)
-    # Note: With current logic this is unreachable (defense-in-depth)
-    if not full_path.is_relative_to(base_dir):  # pragma: no cover
+    # Trusted base directory for served documents
+    documents_base = (Path.cwd() / "documents").resolve()
+    # Normalize target path relative to trusted base
+    full_path = (documents_base / filename).resolve()
+    # Enforce containment: path must be within documents_base (403 if escape attempt)
+    if not full_path.is_relative_to(documents_base):  # pragma: no cover
         return abort(403)
     # Check file exists (404 if not found)
     if not full_path.is_file():
EOF
@@ -140,13 +140,12 @@
Security: Callers must validate that filename is an allowed path.
This function adds defense-in-depth with path normalization and containment.
"""
# Compute base directory from filename's resolved parent
base_dir = Path(filename).resolve().parent
# Normalize target path - only allow basename under resolved parent
full_path = (base_dir / Path(filename).name).resolve()
# Enforce containment: path must be within base_dir (403 if escape attempt)
# Note: With current logic this is unreachable (defense-in-depth)
if not full_path.is_relative_to(base_dir): # pragma: no cover
# Trusted base directory for served documents
documents_base = (Path.cwd() / "documents").resolve()
# Normalize target path relative to trusted base
full_path = (documents_base / filename).resolve()
# Enforce containment: path must be within documents_base (403 if escape attempt)
if not full_path.is_relative_to(documents_base): # pragma: no cover
return abort(403)
# Check file exists (404 if not found)
if not full_path.is_file():
Copilot is powered by AI and may make mistakes. Always verify output.
return abort(404)
base = Path(filename).name
cont_disp = f"inline; filename*=UTF-8''{quote(base)}"
response: Response = send_file(full_path)

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression

This path depends on a [user-provided value](1).

Copilot Autofix

AI 10 months ago

In general, paths derived from untrusted input must be validated before accessing the filesystem. A robust pattern is to (1) define a trusted base directory; (2) construct the target path by joining the base directory with the user-supplied relative name; (3) normalize/resolve the path; and (4) ensure the resolved path is still within the base directory (to prevent directory traversal and absolute-path bypasses). If the check fails, return an error (403/404) instead of accessing the file.

In this codebase, send_file_inline is used as the single helper that actually calls send_file. Callers are supposed to validate filename, but at least one caller (document()) doesn’t. The most targeted, behavior‑preserving fix is therefore:

  • Harden send_file_inline so that it:
    • Resolves the candidate path.
    • Locates the ledger’s configured document root (derived from g.ledger.options["documents"] or a similar attribute).
    • Checks that the resolved file path is within this trusted documents directory (and within the ledger’s root).
    • Rejects any path that falls outside these roots with abort(404) (or 403).
  • To derive the base directories without changing function signatures, we can import g from rustfava.context inside send_file_inline. That object is already used elsewhere in the app and should be available in the request context.
  • Keep using send_file(full_path) and the existing Content-Disposition logic, so the HTTP semantics for valid files remain unchanged.

Concretely, in src/rustfava/util/__init__.py:

  • Add an import for g from rustfava.context.
  • Rewrite send_file_inline to:
    • Attempt to resolve filename to a Path.
    • Determine a base directory (ledger documents directory if available, otherwise the ledger root, and only as a last resort fall back to the original parent to preserve compatibility).
    • Rebuild full_path using the basename of filename under the chosen base directory where appropriate.
    • Enforce full_path.is_file() and containment checks; on failure, abort(404).

No changes are required to src/rustfava/application.py because document() and statement() will automatically benefit from the hardened helper.

Suggested changeset 1
src/rustfava/util/__init__.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/rustfava/util/__init__.py b/src/rustfava/util/__init__.py
--- a/src/rustfava/util/__init__.py
+++ b/src/rustfava/util/__init__.py
@@ -14,6 +14,7 @@
 
 from flask import abort
 from flask import send_file
+from rustfava.context import g
 
 if TYPE_CHECKING:  # pragma: no cover
     from collections.abc import Callable
@@ -140,17 +141,56 @@
     Security: Callers must validate that filename is an allowed path.
     This function adds defense-in-depth with path normalization and containment.
     """
-    # Compute base directory from filename's resolved parent
-    base_dir = Path(filename).resolve().parent
-    # Normalize target path - only allow basename under resolved parent
-    full_path = (base_dir / Path(filename).name).resolve()
-    # Enforce containment: path must be within base_dir (403 if escape attempt)
-    # Note: With current logic this is unreachable (defense-in-depth)
-    if not full_path.is_relative_to(base_dir):  # pragma: no cover
-        return abort(403)
-    # Check file exists (404 if not found)
+    # Resolve the requested path; reject clearly invalid paths early.
+    try:
+        requested_path = Path(filename)
+    except TypeError:
+        return abort(404)
+
+    # Determine a safe base directory from the current ledger context, if available.
+    # Prefer the ledger's documents directory; fall back to the ledger root.
+    base_dir: Path | None = None
+    ledger = getattr(g, "ledger", None)
+    if ledger is not None:
+        documents_dir = getattr(ledger.options, "documents", None)
+        if documents_dir:
+            base_dir = Path(documents_dir).resolve()
+        else:
+            # Use the directory containing the beancount file as a fallback base.
+            beancount_file = getattr(ledger, "beancount_file", None)
+            if beancount_file:
+                base_dir = Path(beancount_file).resolve().parent
+
+    # If we could not determine a base directory from the ledger, use the
+    # resolved parent directory of the requested path as a last resort.
+    # This preserves existing behaviour for internal callers while still
+    # enforcing containment checks below.
+    if base_dir is None:
+        base_dir = requested_path.resolve().parent
+
+    # Construct the final path using the base directory and the requested name.
+    # If the requested path is absolute or contains traversal, this still
+    # results in a path under base_dir when we only take the name component.
+    full_path = (base_dir / requested_path.name).resolve()
+
+    # Enforce containment: the resolved path must be within the chosen base
+    # directory. This prevents directory traversal and absolute-path access.
+    try:
+        is_within_base = full_path.is_relative_to(base_dir)  # type: ignore[attr-defined]
+    except AttributeError:
+        # Python < 3.9: emulate is_relative_to
+        try:
+            full_path.relative_to(base_dir)
+            is_within_base = True
+        except ValueError:
+            is_within_base = False
+    if not is_within_base:
+        return abort(404)
+
+    # Check that the file exists and is a regular file.
     if not full_path.is_file():
         return abort(404)
+
     response: Response = send_file(full_path)
     cont_disp = f"inline; filename*=UTF-8''{quote(full_path.name)}"
     response.headers["Content-Disposition"] = cont_disp
EOF
Copilot is powered by AI and may make mistakes. Always verify output.
robcohen and others added 7 commits January 24, 2026 15:14
Python 3.9+ is_relative_to() doesn't raise ValueError, it returns False.
The try/except was defensive code for older Python versions that this
project no longer supports.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add test for gzip compression of large JSON responses
- Add test for ETag caching returning 304 Not Modified
- Add test for Pydantic validation error handler

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
The target_triple variable used a Unix-specific backtick command that
fails on Windows CI. Changed to use an environment variable with a
default, and detect at runtime in the rustledger-status recipe.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Use Python 3.13 for macOS/Windows tests (beancount lacks 3.14 wheels)
- Fix typeguard NameError by importing Booking directly instead of
  using data.Booking type annotation (forward ref evaluation issue)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Use Any type for Booking to avoid typeguard forward ref evaluation
- Add windows-shell setting to justfile for PowerShell on Windows

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Fix typeguard by using Any for external beancount types (Booking,
  DisplayContext) and importing Decimal at runtime
- Remove unused type: ignore comment in options.py
- Disable Windows tests due to wasmtime WASI path handling issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
The type annotations were changed to Any, making these ignore
comments unnecessary.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants