This commit is contained in:
subodh committed 2026-03-13 14:27:45 +05:30
1 parent d3a5df6387
commit 3fcfce600b
2 files changed
+291 -13

No files matched your search

+290 -13
View File
@@ -1,17 +1,158 @@
import hashlib
import mimetypes
import os
import re
import secrets
import time
from typing import Optional
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile, status
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from slowapi.util import get_remote_address
from app.config.settings import settings
from app.services.r2 import upload_file
UNAUTH_LIMIT = 50 * 1024 * 1024 # 50 MB — unauthenticated
AUTH_LIMIT = 250 * 1024 * 1024 # 250 MB — authenticated
SESSION_DURATION = 24 * 60 * 60 # 24 hours in seconds
# Allowed file extensions (whitelist)
ALLOWED_EXTENSIONS = {
# Images
"jpg",
"jpeg",
"png",
"gif",
"bmp",
"webp",
"svg",
"ico",
"heic",
"heif",
# Documents
"pdf",
"doc",
"docx",
"txt",
"rtf",
"odt",
"xls",
"xlsx",
"csv",
"ppt",
"pptx",
# Archives
"zip",
"rar",
"7z",
"tar",
"gz",
"bz2",
# Audio
"mp3",
"wav",
"ogg",
"flac",
"m4a",
"aac",
# Video
"mp4",
"webm",
"avi",
"mov",
"mkv",
"wmv",
"flv",
# Code/Data
"json",
"xml",
"html",
"css",
"js",
"ts",
"py",
"java",
"c",
"cpp",
"h",
"hpp",
"md",
"yaml",
"yml",
"toml",
"ini",
"cfg",
"conf",
# Fonts
"ttf",
"otf",
"woff",
"woff2",
"eot",
}
# Dangerous extensions that are never allowed
DANGEROUS_EXTENSIONS = {
"exe",
"bat",
"cmd",
"com",
"pif",
"scr",
"vbs",
"vbe",
"ws",
"wsf",
"wsc",
"wsh",
"ps1",
"psc1",
"psc2",
"msc",
"msp",
"hta",
"cpl",
"msi",
"reg",
"lnk",
"inf",
"scf",
"isp",
"stf",
"dll",
"sys",
"drv",
"ocx",
"tlb",
"olb",
"class",
"jar",
"app",
"bundle",
"plugin",
"extension",
}
app = FastAPI(title="File Host API")
# Rate limiter
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_middleware(SlowAPIMiddleware)
@app.exception_handler(RateLimitExceeded)
async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail="Too many requests. Please try again later.",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["https://filehost.subodh.xyz"],
@@ -20,12 +161,102 @@ app.add_middleware(
)
def _resolve_object_name(filename: str, content_type: str) -> str:
def _sanitize_filename(filename: str) -> Optional[str]:
"""
Sanitize filename to prevent path traversal and other attacks.
Returns None if filename is invalid or dangerous.
"""
if not filename:
return None
# Remove null bytes and control characters
filename = re.sub(r"[\x00-\x1f\x7f]", "", filename)
# Decode URL encoding if present
from urllib.parse import unquote
filename = unquote(filename)
# Remove path separators and parent directory references
filename = os.path.basename(filename) # Removes path
filename = re.sub(r"\.\.", "", filename) # Remove any remaining ..
# Remove leading/trailing spaces and dots
filename = filename.strip().strip(".")
if not filename:
return None
# Check for dangerous patterns
if re.search(r'[<>:"|?*]', filename):
return None
# Get extension
ext = ""
if "." in filename:
ext = filename.rsplit(".", 1)[-1].lower().strip()
# Check if extension is dangerous
if ext in DANGEROUS_EXTENSIONS:
return None
# Replace spaces and unsafe characters with underscores
safe_name = re.sub(r"[^a-zA-Z0-9._-]", "_", filename)
# Limit filename length (max 255 bytes for most filesystems)
if len(safe_name.encode("utf-8")) > 255:
# Truncate while preserving extension
if "." in safe_name:
name_part, ext_part = safe_name.rsplit(".", 1)
max_name_len = 255 - len(ext_part) - 1
safe_name = name_part[:max_name_len] + "." + ext_part
else:
safe_name = safe_name[:255]
return safe_name if safe_name else None
def _generate_session_token(password: str) -> dict:
"""Generate a session token with timestamp."""
timestamp = int(time.time())
token_data = f"{password}:{timestamp}"
token = hashlib.sha256(token_data.encode()).hexdigest()
return {"token": token, "timestamp": timestamp}
def _validate_session_token(token: str, timestamp: int) -> bool:
"""Validate a session token using constant-time comparison."""
if not token or not timestamp:
return False
# Check if token has expired
if time.time() - timestamp > SESSION_DURATION:
return False
# Verify token matches current password using constant-time comparison
expected_token = hashlib.sha256(
f"{settings.UPLOAD_PASSWORD}:{timestamp}".encode()
).hexdigest()
return secrets.compare_digest(token, expected_token)
def _resolve_object_name(
filename: str, content_type: str, use_original: bool = False
) -> str:
"""Generate a safe object name for storage."""
if use_original and filename:
safe_name = _sanitize_filename(filename)
if safe_name:
return safe_name
# If sanitization fails, fall through to hashed name
file_id = secrets.token_urlsafe(16)
ext = ""
if filename and "." in filename:
ext = filename.rsplit(".", 1)[-1].strip().lower()
# Sanitize extension
ext = re.sub(r"[^a-z0-9]", "", ext)
if not ext and content_type:
guessed = mimetypes.guess_extension(content_type.split(";")[0].strip())
@@ -36,33 +267,60 @@ def _resolve_object_name(filename: str, content_type: str) -> str:
@app.post("/auth")
async def auth(password: str = Form(...)):
"""Validate the upload password."""
if password != settings.UPLOAD_PASSWORD:
@limiter.limit("5/minute")
async def auth(request: Request, password: str = Form(...)):
"""Validate the upload password and return a session token."""
# Use constant-time comparison for password
if not secrets.compare_digest(password, settings.UPLOAD_PASSWORD):
raise HTTPException(status_code=401, detail="Invalid password.")
return {"valid": True}
session = _generate_session_token(password)
return {"valid": True, **session}
@app.post("/auth/verify")
@limiter.limit("10/minute")
async def auth_verify(
request: Request, token: str = Form(...), timestamp: int = Form(...)
):
"""Verify an existing session token."""
if _validate_session_token(token, timestamp):
return {"valid": True}
raise HTTPException(status_code=401, detail="Invalid or expired session.")
@app.post("/upload")
@limiter.limit("30/minute")
async def upload(
request: Request,
file: UploadFile = File(...),
password: str = Form(default=""),
token: str = Form(default=""),
timestamp: int = Form(default=0),
):
"""
Upload a file to R2.
- No password: allowed up to 50 MB.
- Correct password: allowed up to 250 MB.
- No password/token: allowed up to 50 MB.
- Correct password or valid token: allowed up to 250 MB.
- Wrong password (non-empty): rejected with 401.
"""
if password and password != settings.UPLOAD_PASSWORD:
is_authenticated = False
# Check password auth using constant-time comparison
if password and secrets.compare_digest(password, settings.UPLOAD_PASSWORD):
is_authenticated = True
# Check token auth
elif token and timestamp and _validate_session_token(token, timestamp):
is_authenticated = True
# Reject if password provided but wrong
elif password:
raise HTTPException(status_code=401, detail="Invalid password.")
is_authenticated = password == settings.UPLOAD_PASSWORD
max_size = AUTH_LIMIT if is_authenticated else UNAUTH_LIMIT
limit_str = "250 MB" if is_authenticated else "50 MB"
# Check content-length header first (quick check)
content_length = request.headers.get("content-length")
if content_length and int(content_length) > max_size:
raise HTTPException(
@@ -70,12 +328,31 @@ async def upload(
detail=f"File too large. Maximum allowed size is {limit_str}.",
)
# Read file content to verify actual size
file_content = await file.read()
actual_size = len(file_content)
if actual_size > max_size:
raise HTTPException(
status_code=413,
detail=f"File too large. Maximum allowed size is {limit_str}.",
)
if actual_size == 0:
raise HTTPException(
status_code=400,
detail="Empty file not allowed.",
)
# Reset file pointer for upload
await file.seek(0)
content_type = (
(file.content_type or "application/octet-stream").split(";")[0].strip()
)
object_name = _resolve_object_name(file.filename or "", content_type)
await file.seek(0)
object_name = _resolve_object_name(
file.filename or "", content_type, use_original=is_authenticated
)
try:
url = await upload_file(
+1
View File
@@ -4,3 +4,4 @@ python-multipart
boto3
botocore
pydantic-settings
slowapi