From 7f6ff7f21bf05087f91130f3afcc19c5ffd5eab2 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Thu, 17 Jul 2025 14:57:10 -0400 Subject: [PATCH] refix the raw endpoint --- backend/endpoints/raw.py | 52 +++++++++++++--------------------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/backend/endpoints/raw.py b/backend/endpoints/raw.py index 005919dc7..c4464d63f 100644 --- a/backend/endpoints/raw.py +++ b/backend/endpoints/raw.py @@ -1,11 +1,8 @@ -from pathlib import Path -from typing import Optional - -from config import ASSETS_BASE_PATH from decorators.auth import protected_route from fastapi import HTTPException, Request from fastapi.responses import FileResponse from handler.auth.constants import Scope +from handler.filesystem import fs_asset_handler from utils.router import APIRouter router = APIRouter( @@ -14,40 +11,16 @@ router = APIRouter( ) -def validate_and_resolve_path(path: str) -> Optional[Path]: - try: - user_path = Path(path) - - # Check for explicit parent directory references - if ".." in user_path.parts: - return None - - # Check for absolute paths - if user_path.is_absolute(): - return None - - base_path = Path(ASSETS_BASE_PATH).resolve() - requested_path = (base_path / user_path).resolve() - - # Ensure the resolved path is within the base directory - if not requested_path.is_relative_to(base_path): - return None - - # Check if file exists and is a file (not directory) - if not requested_path.exists() or not requested_path.is_file(): - return None - - return requested_path - except (ValueError, OSError): - return None - - @protected_route(router.head, "/assets/{path:path}", [Scope.ASSETS_READ]) def head_raw_asset(request: Request, path: str): - resolved_path = validate_and_resolve_path(path) + try: + resolved_path = fs_asset_handler.validate_path(path) + except ValueError as exc: + raise HTTPException(status_code=404, detail="Asset not found") from exc - if not resolved_path: - raise HTTPException(status_code=404, detail="Asset not found") + # Check if file exists and is a file (not directory) + if not resolved_path.exists() or not resolved_path.is_file(): + return HTTPException(status_code=404, detail="Asset not found") return FileResponse(path=str(resolved_path), filename=resolved_path.name) @@ -66,7 +39,14 @@ def get_raw_asset(request: Request, path: str): Raises: HTTPException: 404 if asset not found or access denied """ - resolved_path = validate_and_resolve_path(path) + try: + resolved_path = fs_asset_handler.validate_path(path) + except ValueError as exc: + raise HTTPException(status_code=404, detail="Asset not found") from exc + + # Check if file exists and is a file (not directory) + if not resolved_path.exists() or not resolved_path.is_file(): + return HTTPException(status_code=404, detail="Asset not found") if not resolved_path: raise HTTPException(status_code=404, detail="Asset not found")