1. Architecture & Threat Model
Deploying a Python Flask web application (GetApps) on Ubuntu 24.04 LTS behind Cloudflare Zero Trust Tunnel (cloudflared) eliminates direct public exposure of origin ports (80/443/22), while requiring careful application-layer alignment so security controls evaluate the true client IP rather than the local tunnel loopback address.
2. Proxy-Aware Rate Limiting & Security Headers
When traffic arrives through cloudflared / reverse proxies, naive rate limiters key on 127.0.0.1 and inadvertently block all users simultaneously.
from flask import request
def get_real_client_ip() -> str:
"""Resolve real client IP behind trusted Cloudflare Tunnel headers."""
cf_ip = request.headers.get("CF-Connecting-IP")
if cf_ip:
return cf_ip.strip()
xff = request.headers.get("X-Forwarded-For", "")
return xff.split(",")[0].strip() if xff else (request.remote_addr or "127.0.0.1")
Strict HTTP Response Hardening
- Content-Security-Policy (CSP): Restricted script/style/img origins and disallowed inline script execution.
- Session Cookies: Enforced
HttpOnly,Secure, andSameSite=Laxflags. - HTML Sanitization: Applied
bleach.clean()allow-listing strictly safe tags on user-generated review fields.
3. Magic-Byte File Upload Validation
Never trust the Content-Type header or filename extension alone; verify binary file signatures (magic bytes) before saving any uploaded asset.
ALLOWED_SIGNATURES = {
b"\x89PNG\r\n\x1a\n": "png",
b"\xff\xd8\xff": "jpg",
b"RIFF": "webp",
}
def verify_image_magic(stream) -> bool:
header = stream.read(16)
stream.seek(0)
return any(header.startswith(sig) for sig in ALLOWED_SIGNATURES)
4. SSRF-Safe Redirects & SOC Security Audit Dashboard
- Open Redirect / SSRF Mitigation: Validated all
next=redirect parameters usingurlparse()to confirm emptynetlocand relative path prefixes only. - Built-in SOC Security Audit Dashboard: Logged authentication anomalies, rate-limit triggers, rejected file uploads, and CSRF failures into structured audit trails for immediate visibility.
5. Verification Results
pytest -v --tb=short
# Result: 151 passed in 4.82s (0 failed, 0 skipped)