added more security to dockerfile

This commit is contained in:
juancarlos.cavero 2025-12-19 18:24:57 +01:00
parent d5121ed9dd
commit f7cc7b8fe3
2 changed files with 67 additions and 9 deletions

View file

@ -8,9 +8,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \ build-essential \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Copy and install Python dependencies
# Copy and install Python dependencies # Copy and install Python dependencies
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir -r requirements.txt
# Final stage # Final stage
FROM python:3.11-slim FROM python:3.11-slim
@ -27,17 +30,25 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libxrender1 \ libxrender1 \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
# Copy installed packages from builder # Copy virtual env from builder
COPY --from=builder /root/.local /root/.local COPY --from=builder /opt/venv /opt/venv
ENV PATH=/root/.local/bin:$PATH ENV PATH="/opt/venv/bin:$PATH"
# Copy application code # Copy application code
COPY . . COPY . .
# Create directories for input/output videos # Create a non-root user (Moved up)
RUN mkdir -p /app/uploads /app/output RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser
# Pre-download YOLO model on build (optional, speeds up first run) # Create directories including Ultralytics cache config
RUN mkdir -p /app/uploads /app/output /tmp/Ultralytics
# Fix permissions: /app for code/uploads, /tmp/Ultralytics for AI cache
RUN chown -R appuser:appuser /app /tmp/Ultralytics
# Switch to non-root user
USER appuser
# Pre-download YOLO model on build (now running as appuser)
RUN python -c "from ultralytics import YOLO; YOLO('yolov8n.pt')" RUN python -c "from ultralytics import YOLO; YOLO('yolov8n.pt')"
# Expose FastAPI port # Expose FastAPI port

51
app.py
View file

@ -22,6 +22,8 @@ os.makedirs(OUTPUT_DIR, exist_ok=True)
# Configuration # Configuration
# Default to 1 if not set, but user can set higher for powerful servers # Default to 1 if not set, but user can set higher for powerful servers
MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "1")) MAX_CONCURRENT_JOBS = int(os.environ.get("MAX_CONCURRENT_JOBS", "1"))
MAX_FILE_SIZE_MB = 500 # 500 MB limit
JOB_RETENTION_SECONDS = 3600 # 1 hour retention
# Application State # Application State
job_queue = asyncio.Queue() job_queue = asyncio.Queue()
@ -29,6 +31,37 @@ jobs: Dict[str, Dict] = {}
# Semester to limit concurrency to MAX_CONCURRENT_JOBS # Semester to limit concurrency to MAX_CONCURRENT_JOBS
concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS) concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS)
async def cleanup_jobs():
"""Background task to remove old jobs and files."""
import time
print("🧹 Cleanup task started.")
while True:
try:
await asyncio.sleep(300) # Check every 5 minutes
now = time.time()
# Simple directory cleanup based on modification time
# Check OUTPUT_DIR
for job_id in os.listdir(OUTPUT_DIR):
job_path = os.path.join(OUTPUT_DIR, job_id)
if os.path.isdir(job_path):
if now - os.path.getmtime(job_path) > JOB_RETENTION_SECONDS:
print(f"🧹 Purging old job: {job_id}")
shutil.rmtree(job_path, ignore_errors=True)
if job_id in jobs:
del jobs[job_id]
# Cleanup Uploads
for filename in os.listdir(UPLOAD_DIR):
file_path = os.path.join(UPLOAD_DIR, filename)
try:
if now - os.path.getmtime(file_path) > JOB_RETENTION_SECONDS:
os.remove(file_path)
except Exception: pass
except Exception as e:
print(f"⚠️ Cleanup error: {e}")
async def process_queue(): async def process_queue():
"""Background worker to process jobs from the queue with concurrency limit.""" """Background worker to process jobs from the queue with concurrency limit."""
print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.") print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.")
@ -64,8 +97,9 @@ async def run_job_wrapper(job_id):
@asynccontextmanager @asynccontextmanager
async def lifespan(app: FastAPI): async def lifespan(app: FastAPI):
# Start worker # Start worker and cleanup
worker_task = asyncio.create_task(process_queue()) worker_task = asyncio.create_task(process_queue())
cleanup_task = asyncio.create_task(cleanup_jobs())
yield yield
# Cleanup (optional: cancel worker) # Cleanup (optional: cancel worker)
@ -190,9 +224,22 @@ async def process_endpoint(
if url: if url:
cmd.extend(["-u", url]) cmd.extend(["-u", url])
else: else:
# Save uploaded file with size limit check
input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{file.filename}") input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{file.filename}")
# Read file in chunks to check size
size = 0
limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024
with open(input_path, "wb") as buffer: with open(input_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer) while content := await file.read(1024 * 1024): # Read 1MB chunks
size += len(content)
if size > limit_bytes:
os.remove(input_path)
shutil.rmtree(job_output_dir)
raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB")
buffer.write(content)
cmd.extend(["-i", input_path]) cmd.extend(["-i", input_path])
cmd.extend(["-o", job_output_dir]) cmd.extend(["-o", job_output_dir])