Skip to content

refactor: extract _validate_safe_path into utils/validation.py for reuse across routers #41

Open

Description

@SckyzO

refactor: extract _validate_safe_path into utils/validation.py for reuse across routers

Symptom

Path-traversal validation logic exists in src/rackscope/api/routers/checks.py:33-40 as a local helper:

def _validate_safe_path(name: str, base_dir: Path) -> Path:
    """Validate that a user-supplied filename stays within base_dir.

    Raises HTTPException 400 if name contains traversal sequences.
    """
    target = (base_dir / name).resolve()
    if not str(target).startswith(str(base_dir.resolve()) + "/"):
        raise HTTPException(status_code=400, detail="Invalid filename")
    return target

It is used at checks.py:88 and checks.py:109 to protect GET /api/checks/files/{name} and PUT /api/checks/files/{name} from path-traversal attacks via the name parameter.

A similar (but separate) implementation exists in metrics.py for the same purpose. Future routers handling user-supplied filenames (e.g., topology import/export, plugin config files served by name, attachment uploads) will need the same primitive — and either duplicate it or risk forgetting it entirely.

This is the audit recommendation R2: extract the helper into the shared utility module so every router uses the same battle-tested implementation.

Technical Analysis

src/rackscope/utils/validation.py already exists and hosts assert_safe_id() — the equivalent primitive for path components (no slashes, no .., no shell specials). Adding the path containment check next to it is the natural placement.

The two functions serve complementary purposes:

  • assert_safe_id(value, field_name) — validates a single ID-shaped string (no slashes, no traversal sequences, no shell specials). Used on path parameters that become parts of filesystem paths.
  • assert_safe_path(name, base_dir) -> Path — given a user-supplied filename and a base directory, returns the resolved absolute path only if it stays within base_dir. Used when constructing the actual filesystem operation.

They are not interchangeable. assert_safe_id rejects ../etc/passwd at parse time; assert_safe_path rejects symlinked attacks where a "clean-looking" filename resolves outside base_dir.

Proposed Fix

1. Add assert_safe_path to utils/validation.py

# src/rackscope/utils/validation.py — add to existing file
from pathlib import Path
from fastapi import HTTPException


def assert_safe_path(name: str, base_dir: Path) -> Path:
    """Return the resolved path of `name` under `base_dir`, or raise HTTPException 400.

    The check uses Path.resolve() to follow symlinks and detect attempts to
    escape `base_dir` via traversal sequences (../) or absolute paths. The
    returned Path is guaranteed to be inside `base_dir` after resolution.

    Args:
        name: User-supplied filename. May contain a subdirectory component.
        base_dir: The directory the result must stay within.

    Raises:
        HTTPException(400): if the resolved path escapes base_dir.
    """
    target = (base_dir / name).resolve()
    base_resolved = base_dir.resolve()
    # Compare as Path components, not string prefixes, to avoid the
    # "/a/b/" vs "/a/bc/" prefix-match trap.
    try:
        target.relative_to(base_resolved)
    except ValueError:
        raise HTTPException(status_code=400, detail="Invalid filename")
    return target

Implementation refinement vs the existing checks.py version:

  • Uses Path.relative_to() instead of string-prefix comparison. The string-prefix approach has the historical pitfall that "/var/data/foo" is a prefix of "/var/data/foo-bar/x" — relative_to correctly distinguishes these.
  • Equivalent guarantee, slightly more robust shape. Include a one-line comment in the code (matching PROFILE_DEV rule for non-obvious "why") explaining why relative_to is preferred.

2. Migrate checks.py to the new utility

# src/rackscope/api/routers/checks.py
-from pathlib import Path
+from pathlib import Path
+from rackscope.utils.validation import assert_safe_path

-def _validate_safe_path(name: str, base_dir: Path) -> Path:
-    """Validate that a user-supplied filename stays within base_dir.
-
-    Raises HTTPException 400 if name contains traversal sequences.
-    """
-    target = (base_dir / name).resolve()
-    if not str(target).startswith(str(base_dir.resolve()) + "/"):
-        raise HTTPException(status_code=400, detail="Invalid filename")
-    return target

 @router.get("/files/{name}")
 def get_checks_file(...):
     ...
-    target = _validate_safe_path(name, base_dir)
+    target = assert_safe_path(name, base_dir)
     ...

3. Audit metrics.py for the same pattern

Confirm whether metrics.py has its own _validate_safe_path implementation and migrate it the same way. If the existing implementation differs in any meaningful way (e.g., handles a special case), reconcile the differences in assert_safe_path so the unified helper covers both.

Document any reconciliation decisions in the PR description.

4. Document for plugin authors

Add a short section to the plugin development guide (rackscope_documentation/docs/plugins/) explaining the two complementary primitives:

Validating user-supplied filenames

Two helpers in rackscope.utils.validation:

  • assert_safe_id(value, field_name) — for path-component-shaped IDs (no slashes, no traversal). Use it on FastAPI path parameters.
  • assert_safe_path(name, base_dir) -> Path — for filenames that map to real filesystem paths. Use it when building the actual open() / read_text() / write_text() argument.

Test Checklist

Unit tests on assert_safe_path

  • tests/unit/utils/test_assert_safe_path.py: clean filename "foo.yml" resolves under base_dir → returns the resolved Path
  • Traversal "../etc/passwd" → raises HTTPException(400)
  • Absolute path "/etc/passwd" → raises HTTPException(400)
  • Prefix-trap: base_dir=/var/data, name resolving to /var/data-other/x → raises (regression guard on the relative_to improvement)
  • Symlink escape: in a tmp_path setup, create a symlink that points outside base_dir, then call with the symlink's name → raises (confirms .resolve() is doing its job)
  • Empty name "" → raises (well-defined behaviour, probably 400)
  • Subdirectory component "sub/file.yml" → returns resolved path if it stays under base_dir and the subdir exists

Functional tests

  • Existing checks.py test suite passes after the migration (same 400 shape preserved on the same inputs)
  • Same for metrics.py after its migration
  • _validate_safe_path is no longer defined in checks.py (grep confirmation in the PR)

Non-regression

  • Every 400 Invalid filename response shape is identical pre and post (frontend handlers depend on the exact detail string)

Impact and Severity

  • Audience affected: contributors (cleaner code), and indirectly users (slightly more robust path validation via the relative_to improvement).
  • Severity: low. The validation already works correctly; this is consolidation, not a vulnerability fix.
  • Priority: Sprint 4 of the audit roadmap. Ships when convenient. Good "first contribution" candidate.

Breaking Changes

None. The exposed validation behaviour is identical (slightly more robust on edge cases via relative_to, but no false-positive regression expected).

Related

Out of Scope

  • Auditing every router for missing path validation — this PR consolidates the existing implementations; a separate audit for unprotected file-handling endpoints is filed if needed (none currently flagged).
  • Adding rate-limiting on file-read endpoints — out of scope.
  • A general-purpose SafePath Pydantic type — possible v2 evolution, not needed for this refactor.

Activity

  1. added
    enhancement
    on May 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions