Add CORS, rate limiting, security headers, and files endpoint protection
This commit is contained in:
@@ -1,24 +1,33 @@
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from fastapi import APIRouter, UploadFile, File
|
||||
from fastapi import APIRouter, UploadFile, File, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from config import VOLUME_ROOT
|
||||
|
||||
router = APIRouter()
|
||||
BASE = Path(VOLUME_ROOT)
|
||||
|
||||
BLOCKED_DIRS = {"@appstore", "@docker", "@eaDir", "@S2S", "@sharesnap", "@tmp"}
|
||||
|
||||
|
||||
def _safe_path(path: str) -> Path:
|
||||
target = (BASE / path).resolve()
|
||||
if not str(target).startswith(str(BASE.resolve())):
|
||||
raise ValueError("forbidden")
|
||||
# Block access to sensitive directories
|
||||
rel = target.relative_to(BASE.resolve())
|
||||
if rel.parts and rel.parts[0] in BLOCKED_DIRS:
|
||||
raise ValueError("forbidden")
|
||||
return target
|
||||
|
||||
|
||||
@router.get("/browse")
|
||||
def browse(path: str = ""):
|
||||
target = _safe_path(path)
|
||||
try:
|
||||
target = _safe_path(path)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
entries = []
|
||||
for item in sorted(target.iterdir()):
|
||||
try:
|
||||
@@ -31,12 +40,18 @@ def browse(path: str = ""):
|
||||
|
||||
@router.get("/download")
|
||||
def download(path: str):
|
||||
return FileResponse(_safe_path(path))
|
||||
try:
|
||||
return FileResponse(_safe_path(path))
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload(path: str, file: UploadFile = File(...)):
|
||||
target = _safe_path(path) / file.filename
|
||||
try:
|
||||
target = _safe_path(path) / file.filename
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
with open(target, "wb") as f:
|
||||
shutil.copyfileobj(file.file, f)
|
||||
return {"ok": True}
|
||||
@@ -44,7 +59,10 @@ async def upload(path: str, file: UploadFile = File(...)):
|
||||
|
||||
@router.delete("/delete")
|
||||
def delete(path: str):
|
||||
target = _safe_path(path)
|
||||
try:
|
||||
target = _safe_path(path)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
if target.is_dir():
|
||||
shutil.rmtree(target)
|
||||
else:
|
||||
|
||||
Reference in New Issue
Block a user