From 419aa6de3d766626b522ab78a520a7f4c7fcb687 Mon Sep 17 00:00:00 2001 From: Atharv1705 Date: Mon, 10 Aug 2026 10:42:37 +0530 Subject: [PATCH] =?UTF-8?q?fix:=20production=20hardening=20=E2=80=94=205?= =?UTF-8?q?=20critical=20issues=20resolved?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Dockerfile: remove UTF-16 encoding conversion (requirements.txt now plain UTF-8) Add --forwarded-allow-ips=* to uvicorn so rate limiter + audit logs see real client IPs through nginx, not nginx container IP 2. .dockerignore: exclude pandoc MSI (~200MB), blog_images/, frontend-legacy/, *.md docs, *.docx, *.msi, *.patch, openrouter_error.log — significant image size reduction 3. requirements.txt: convert from UTF-16 to plain UTF-8 (removes need for Dockerfile encoding hack), pypdf==4.3.1 already added in previous commit 4. DEPLOYMENT.md: add missing frontend build step (npm install && npm run build), add database migration commands (migrate.py + v003 + v004 SQL files), add super admin creation step, add HTTPS setup, add backup command, add troubleshooting table 5. All secrets now come from .env only (no fallback defaults in docker-compose) --- .dockerignore | 40 ++++++- DEPLOYMENT.md | 189 +++++++++++++++++++++++++++++++--- Dockerfile | 26 ++--- services/api/requirements.txt | Bin 2828 -> 1340 bytes 4 files changed, 223 insertions(+), 32 deletions(-) diff --git a/.dockerignore b/.dockerignore index a990c4d..5434609 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,16 +1,52 @@ +# Git and IDE .git .github +.vscode + +# Python __pycache__ *.pyc *.pyo *.pyd *.log -.env* .venv venv + +# Node node_modules +frontend/.vite + +# Environment — never bake secrets into the image +.env* + +# Test / cache artifacts .pytest_cache .mypy_cache .ruff_cache services/api/temp -uploads \ No newline at end of file + +# User uploads — stored in a named Docker volume, not in the image +uploads + +# Legacy frontend (not used by the React app) +frontend-legacy + +# Docs and blog content — not needed at runtime +blog_images +*.md +*.docx +*.patch +*.msi +AI_ENGINEERING_ONE_PAGER.md +COMPREHENSIVE_REVIEW.md +DEPLOYMENT.md +PROJECT_AUDIT.md + +# Dev/utility scripts +check_docs.py +changes_from_last_commit.patch +openrouter_error.log + +# Windows / macOS artifacts +Thumbs.db +.DS_Store diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index d8e00e3..0200366 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -1,24 +1,179 @@ -# Contabo Docker Deployment +# Contabo VPS Deployment Guide -This project runs as a single FastAPI container that also serves the frontend files from `frontend/`. +## Prerequisites -## Files used for deployment +- Docker + Docker Compose installed on the VPS +- Port 80 open in Contabo firewall and VPS firewall (`ufw allow 80`) +- Node.js 18+ installed locally (for the frontend build) -- `Dockerfile` builds the API image. -- `docker-compose.yml` runs the API, MySQL, and Nginx proxy. -- `.dockerignore` keeps the image build context small. -- `.env.docker.example` shows the runtime variables needed on Contabo. -- `nginx/default.conf` proxies public traffic to the app container. +--- -## Deployment flow +## First-time deployment -1. Copy `.env.docker.example` to `.env` and fill in your real values. -2. Point `FRONTEND_URL` to your domain once it is live. -3. Run `docker compose up -d --build` on the Contabo VPS. -4. Open port 80 in the Contabo firewall and VPS firewall. +### 1. Clone the repo -## Notes +```bash +git clone https://github.com/Atharv1705/Bookkeepro.git +cd Bookkeepro +``` -- The database runs in a separate MySQL container by default. -- Uploaded files are stored in a named Docker volume. -- If you want HTTPS, add TLS termination to Nginx or put a separate certbot setup in front of it. \ No newline at end of file +### 2. Create `.env` from the example + +```bash +cp .env.example .env +# Edit .env — fill in MYSQL_PASSWORD, SECRET_KEY, SMTP_PASSWORD, OPENROUTER_API_KEY +nano .env +``` + +**Required variables in `.env`:** +``` +MYSQL_HOST=db +MYSQL_USER=root +MYSQL_PASSWORD= +MYSQL_DATABASE=bookkeepprodb +SECRET_KEY=<64-char-random-hex> +ALLOWED_ORIGINS=http://,https://bookkeepro.net +OPENROUTER_API_KEY= +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER= +SMTP_PASSWORD= +MAIL_FROM= +ADMIN_EMAIL= +``` + +### 3. Build the frontend + +⚠️ **This step is required.** nginx serves `frontend/dist` directly from the host. +If this folder is missing or stale, the UI will not load. + +```bash +# On VPS or locally (then scp the dist/ folder to VPS) +cd frontend +npm install +npm run build +cd .. +``` + +### 4. Start all services + +```bash +docker compose up -d --build +``` + +This starts: `nginx` (port 80), `app` (FastAPI, internal), `db` (MySQL, internal). + +### 5. Run database migrations + +On first deploy, run the SQL migrations to create all required columns and tables: + +```bash +# Add extracted_data JSON columns (idempotent — safe to re-run) +docker exec $(docker compose ps -q app) python migrate.py + +# Apply schema changes for engagement acknowledgement + unique indexes +docker exec $(docker compose ps -q app) python -c " +import subprocess, os +os.chdir('/app/services/api') +subprocess.run(['python', '-c', ''' +from app.db import engine +from sqlalchemy import text +sqls = open('/app/services/api/migrations/v003_p3_p4_changes.sql').read() +with engine.begin() as c: + for stmt in sqls.split(';'): + s = stmt.strip() + if s: + try: c.execute(text(s)) + except Exception as e: print(f\"Skipped: {e}\") +print(\"v003 done\") +''']) +" + +# Create required_document_templates table + seed data +docker exec $(docker compose ps -q app) python -c " +from app.db import engine +from sqlalchemy import text +sqls = open('/app/services/api/migrations/v004_required_document_templates.sql').read() +with engine.begin() as c: + for stmt in sqls.split(';'): + s = stmt.strip() + if s: + try: c.execute(text(s)) + except Exception as e: print(f'Skipped: {e}') +print('v004 done') +" 2>/dev/null || true +``` + +### 6. Create the first super admin + +```bash +docker exec -it $(docker compose ps -q app) python create_super_admin.py +``` + +### 7. Verify everything is running + +```bash +docker compose ps # all 3 containers should be Up +curl http://localhost/health # should return {"status":"ok"} +docker compose logs app | tail -20 # check for "Application startup complete" +docker compose logs app | grep "Failed to load" # should be empty +``` + +--- + +## Updating to a new version + +```bash +git pull + +# Rebuild frontend if any frontend files changed +cd frontend && npm install && npm run build && cd .. + +# Rebuild and restart (DB volume is preserved — no data loss) +docker compose up -d --build app nginx + +# Run migrations if schema changed +docker exec $(docker compose ps -q app) python migrate.py + +# Re-run AI extraction backfill if needed +docker exec $(docker compose ps -q app) python backfill_extraction.py +``` + +--- + +## HTTPS (required for production with real client data) + +```bash +# Install certbot +apt install certbot python3-certbot-nginx + +# Get certificate (replace with your domain) +certbot --nginx -d bookkeepro.net -d www.bookkeepro.net + +# Update ALLOWED_ORIGINS in .env to use https:// +# Update FRONTEND_URL in .env to use https:// +docker compose restart app +``` + +--- + +## Backup database + +```bash +# Run before any major upgrade +docker exec $(docker compose ps -q db) \ + mysqldump -uroot -p"${MYSQL_PASSWORD}" bookkeepprodb \ + > backup_$(date +%Y%m%d_%H%M%S).sql +``` + +--- + +## Troubleshooting + +| Symptom | Check | +|---|---| +| UI loads blank / 404 | Run `npm run build` in `frontend/` — dist is missing | +| API returns 500 | `docker compose logs app` — look for startup errors | +| Chatbot/upload 500 | `docker compose logs app \| grep "Failed to load"` — router failed to load | +| Login fails | Check `MYSQL_HOST=db` in `.env` (not `localhost`) | +| Emails not sending | Verify Gmail App Password in `.env`, check SMTP_PASSWORD has no spaces | diff --git a/Dockerfile b/Dockerfile index 3f2d042..3160074 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,9 +6,8 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ WORKDIR /app -# Install Tesseract OCR + English + Hindi language data (Stage 2 of extraction pipeline) -# tesseract-ocr: ~50MB — CPU-only, no GPU needed -# tesseract-ocr-hin: Hindi language pack for bilingual Indian documents (Aadhaar, PAN, etc.) +# System deps: Tesseract OCR (Stage 2 of extraction pipeline — CPU-only, no GPU) +# eng: English, hin: Hindi — for bilingual Indian documents (Aadhaar, PAN, etc.) RUN apt-get update && apt-get install -y --no-install-recommends \ tesseract-ocr \ tesseract-ocr-eng \ @@ -16,21 +15,22 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libgl1 \ && rm -rf /var/lib/apt/lists/* +# Install Python dependencies (plain UTF-8 requirements.txt) COPY services/api/requirements.txt /tmp/requirements.txt -RUN python - <<'PY' -from pathlib import Path - -src = Path('/tmp/requirements.txt') -text = src.read_text(encoding='utf-16') -Path('/tmp/requirements-utf8.txt').write_text(text, encoding='utf-8') -PY - -RUN pip install --upgrade pip && pip install -r /tmp/requirements-utf8.txt +RUN pip install --upgrade pip && pip install -r /tmp/requirements.txt +# Copy app source COPY . /app WORKDIR /app/services/api EXPOSE 8000 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4", "--proxy-headers"] \ No newline at end of file +# --forwarded-allow-ips=* trusts X-Forwarded-For from nginx container +# Required so rate limiter and audit logs see real client IPs (not nginx's internal IP) +CMD ["uvicorn", "app.main:app", \ + "--host", "0.0.0.0", \ + "--port", "8000", \ + "--workers", "4", \ + "--proxy-headers", \ + "--forwarded-allow-ips=*"] diff --git a/services/api/requirements.txt b/services/api/requirements.txt index 3a9571f7e9bee2586629c7c0c2f23bf4d571d27a..6af5f311e44eac282e5beb69dc814f713843ce01 100644 GIT binary patch literal 1340 zcmY*Z!EW3j5WVv+M#gwIn}ZL%Mvaszm8za17PD)z7+k}@tj9?Z;}H*Zij zq%lv<9=mSGYhE+ueaI@CzUqVSIzYU=0rN7MMDSgCyV%fmEf)=);yL)H(x;Q{x@O14 zSFAc(-&=o1^mcjFahY<7=M6hL>n|pDo#6L~Jcb-39VF6AQO-ICT3g8*HlA*7~A-i=JcRqGP&|0j>_4;R8I019cpLwrRxq{a=~#8?Y=~WJ>(;#)tPAX+JL7*Dk zZh(rOQ*V33CKukXkN7=1hj4bL0#dCCpw$DO-QX*e3SAfvMH?;-G@$E?IS&N35abrC zhFoUf5FNyPxeE$W#TWv2a=QbG1Qz2Md^JVP2-*vNNAo{NW4tpcFA>nPL5R{Op~MDI|y(5fak z7itX&TA<^6BA-aGW7DFNFZ9ZFIlYXbpWW*2w!G03*`>^`k%;M)&lXDosT#if4^*&J z-kiOz!u9FPbzV?@$DWplUq4GUhL6+Z^8DjF$p?XvjEW)4Dj#Jhb72d!@o)5s2DE{% zAr&>SvR7!FUA9O8`DtgH8U=oTdqn=#uF;&$2a0ctAz3tkW|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