tinycodinglm / code /appdev-0060.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.37 kB
opencode trace
System You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing c...

You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies.

User

How do I build a secure FastAPI file manager with upload, download, delete and listing? Show filename sanitization against path traversal and XSS-safe rendering. Include code examples.

Assistant

Secure file manager - always sanitize UploadFile.filename (see CVE-2026-85684 path-traversal class).

python
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
from pathlib import Path
import shutil
import re

app = FastAPI()
UPLOAD_DIR = Path("uploads").resolve()
UPLOAD_DIR.mkdir(exist_ok=True)
SAFE_NAME = re.compile(r"^[A-Za-z0-9._-]{1,64}$")

def safe_path(filename: str) -> Path:
    name = Path(filename or "").name  # strip directories
    if not SAFE_NAME.match(name):
        raise HTTPException(400, "Unsafe filename")
    p = (UPLOAD_DIR / name).resolve()
    if p.parent != UPLOAD_DIR:
        raise HTTPException(400, "Path escapes upload dir")
    return p

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    if file.size and file.size > 10 * 1024 * 1024:
        raise HTTPException(413, "Too large")
    dest = safe_path(file.filename or "upload.bin")
    with open(dest, "wb") as f:
        shutil.copyfileobj(file.file, f)
    return {"filename": dest.name}

@app.get("/download/{filename}")
def download_file(filename: str):
    path = safe_path(filename)
    if not path.exists():
        raise HTTPException(404, "Not found")
    return FileResponse(path, filename=path.name)

Frontend: use textContent, never innerHTML, with allowlisted extensions, size limits, and auth. Raw UPLOAD_DIR / file.filename allows ../../ traversal - never use it.