#!/usr/bin/env python3
"""
Security Audit Report Generator for SumoPod.com
Author: Eko Budi
Date: 2026-07-26
"""

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, PageBreak, Table, TableStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from datetime import datetime

def create_security_report():
    """Generate comprehensive security audit PDF report"""
    
    # Create PDF
    pdf_file = "SumoPod_Security_Audit_Report_2026-07-26.pdf"
    doc = SimpleDocTemplate(pdf_file, pagesize=A4,
                            topMargin=2*cm, bottomMargin=2*cm,
                            leftMargin=2.5*cm, rightMargin=2.5*cm)
    
    # Styles
    styles = getSampleStyleSheet()
    
    # Custom styles
    title_style = ParagraphStyle(
        'CustomTitle',
        parent=styles['Title'],
        fontSize=24,
        textColor=colors.HexColor('#1a1a1a'),
        spaceAfter=30,
        alignment=TA_CENTER
    )
    
    heading1_style = ParagraphStyle(
        'CustomHeading1',
        parent=styles['Heading1'],
        fontSize=16,
        textColor=colors.HexColor('#c70000'),
        spaceAfter=12,
        spaceBefore=20
    )
    
    heading2_style = ParagraphStyle(
        'CustomHeading2',
        parent=styles['Heading2'],
        fontSize=14,
        textColor=colors.HexColor('#333333'),
        spaceAfter=10,
        spaceBefore=15
    )
    
    body_style = ParagraphStyle(
        'CustomBody',
        parent=styles['Normal'],
        fontSize=10,
        alignment=TA_JUSTIFY,
        spaceAfter=8
    )
    
    code_style = ParagraphStyle(
        'Code',
        parent=styles['Normal'],
        fontSize=8,
        fontName='Courier',
        textColor=colors.HexColor('#666666'),
        leftIndent=20,
        spaceAfter=10,
        backColor=colors.HexColor('#f5f5f5')
    )
    
    # Story (content container)
    story = []
    
    # ========== COVER PAGE ==========
    story.append(Spacer(1, 3*cm))
    story.append(Paragraph("SECURITY AUDIT REPORT", title_style))
    story.append(Spacer(1, 0.5*cm))
    story.append(Paragraph("SumoPod.com", styles['Title']))
    story.append(Spacer(1, 2*cm))
    
    story.append(Paragraph("<b>Auditor:</b> Eko Budi", body_style))
    story.append(Paragraph(f"<b>Date:</b> {datetime.now().strftime('%d %B %Y')}", body_style))
    story.append(Paragraph("<b>Target:</b> https://sumopod.com", body_style))
    story.append(Spacer(1, 1*cm))
    
    story.append(Paragraph("<b>Classification:</b> CONFIDENTIAL", body_style))
    story.append(PageBreak())
    
    # ========== EXECUTIVE SUMMARY ==========
    story.append(Paragraph("EXECUTIVE SUMMARY", heading1_style))
    story.append(Paragraph(
        "This security audit was conducted on SumoPod.com on July 26, 2026, focusing on publicly "
        "accessible endpoints, JavaScript bundle analysis, and backend API exposure. The assessment "
        "revealed several critical and high-severity security vulnerabilities that require immediate attention.",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    # Summary table
    summary_data = [
        ['Severity', 'Count', 'Status'],
        ['CRITICAL', '2', 'Requires immediate action'],
        ['HIGH', '1', 'Requires urgent attention'],
        ['MEDIUM', '4', 'Should be addressed'],
        ['LOW', '2', 'Good to fix']
    ]
    
    summary_table = Table(summary_data, colWidths=[4*cm, 3*cm, 7*cm])
    summary_table.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#333333')),
        ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
        ('FONTSIZE', (0, 0), (-1, 0), 10),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
        ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white, colors.HexColor('#f5f5f5')])
    ]))
    
    story.append(summary_table)
    story.append(PageBreak())
    
    # ========== CRITICAL FINDINGS ==========
    story.append(Paragraph("1. CRITICAL FINDINGS", heading1_style))
    
    # Finding 1
    story.append(Paragraph("1.1 Supabase Anonymous Key Exposed in JavaScript Bundle", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='red'>CRITICAL</font>", body_style))
    story.append(Paragraph("<b>CVSS Score:</b> 9.1 (Critical)", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "The Supabase anonymous API key is hardcoded and publicly visible in the JavaScript bundle "
        "served at <font face='Courier'>/assets/index-C1Pn7-qa.js</font>. This key provides direct "
        "access to the Supabase backend database.",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Evidence:</b>", body_style))
    story.append(Paragraph(
        "<font face='Courier' size='7'>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImRoc3J3YnVmcGR2dXB0ZHplaWVvIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDY0NTQ4NTUsImV4cCI6MjA2MjAzMDg1NX0.7dhHHFZZArMOQgFwehICyjY-QKehZ9gvrVt8hOXTJX0</font>",
        code_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>JWT Decoded:</b>", body_style))
    story.append(Paragraph(
        "<font face='Courier' size='8'>{<br/>"
        "&nbsp;&nbsp;\"iss\": \"supabase\",<br/>"
        "&nbsp;&nbsp;\"ref\": \"dhsrwbufpdvuptdzeieo\",<br/>"
        "&nbsp;&nbsp;\"role\": \"anon\",<br/>"
        "&nbsp;&nbsp;\"iat\": 1746454855,<br/>"
        "&nbsp;&nbsp;\"exp\": 2062030855&nbsp;&nbsp;// Expires in 2062 (36 years)<br/>"
        "}</font>",
        code_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Impact:</b>", body_style))
    story.append(Paragraph(
        "• Attackers can query Supabase database directly<br/>"
        "• Potential data exfiltration if RLS is misconfigured<br/>"
        "• API abuse for DoS attacks<br/>"
        "• Long expiration (36 years) means key remains valid indefinitely",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Mitigation Status:</b>", body_style))
    story.append(Paragraph(
        "✅ Row Level Security (RLS) is ACTIVE — tested queries returned empty arrays, "
        "indicating proper data protection despite key exposure.",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Recommendations:</b>", body_style))
    story.append(Paragraph(
        "1. Rotate Supabase anonymous key immediately<br/>"
        "2. Set shorter expiration period (max 1 year)<br/>"
        "3. Implement rate limiting at Supabase level<br/>"
        "4. Audit all RLS policies for potential misconfigurations<br/>"
        "5. Use environment-based keys (dev vs prod)",
        body_style
    ))
    
    story.append(PageBreak())
    
    # Finding 2
    story.append(Paragraph("1.2 Verbose Error Messages Exposing Backend Architecture", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='red'>CRITICAL</font>", body_style))
    story.append(Paragraph("<b>CVSS Score:</b> 7.5 (High)", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "Error messages from Supabase and Kong API Gateway reveal internal architecture details, "
        "including hints about privileged access keys and database table structure.",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Evidence:</b>", body_style))
    story.append(Paragraph(
        "<font face='Courier' size='8'>{<br/>"
        "&nbsp;&nbsp;\"message\": \"Invalid API key\",<br/>"
        "&nbsp;&nbsp;\"hint\": \"Only the `service_role` API key can be used for this endpoint.\"<br/>"
        "}</font>",
        code_style
    ))
    story.append(Paragraph(
        "<font face='Courier' size='8'>{<br/>"
        "&nbsp;&nbsp;\"message\": \"Could not find the table 'public.merchants'\",<br/>"
        "&nbsp;&nbsp;\"hint\": \"Perhaps you meant the table 'public.payments'\"<br/>"
        "}</font>",
        code_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Impact:</b>", body_style))
    story.append(Paragraph(
        "• Reveals existence of privileged <font face='Courier'>service_role</font> key<br/>"
        "• Discloses database table names (<font face='Courier'>ai_users</font>, <font face='Courier'>payments</font>)<br/>"
        "• Provides roadmap for targeted attacks<br/>"
        "• Violates security by obscurity principles",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Recommendations:</b>", body_style))
    story.append(Paragraph(
        "1. Return generic error messages (401 Unauthorized, 403 Forbidden)<br/>"
        "2. Remove all hints from production error responses<br/>"
        "3. Log detailed errors server-side only<br/>"
        "4. Implement error message sanitization middleware",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== HIGH SEVERITY ==========
    story.append(Paragraph("2. HIGH SEVERITY FINDINGS", heading1_style))
    
    story.append(Paragraph("2.1 Sandbox Payment API Publicly Accessible", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='orange'>HIGH</font>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "The sandbox payment API endpoint <font face='Courier'>api-pay-sandbox.sumopod.com</font> "
        "is reachable from the public internet without IP restrictions.",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Impact:</b>", body_style))
    story.append(Paragraph(
        "• Sandbox environments should be internal-only<br/>"
        "• Exposes test payment flows to attackers<br/>"
        "• Potential for staging data leakage<br/>"
        "• Increases attack surface unnecessarily",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Recommendations:</b>", body_style))
    story.append(Paragraph(
        "1. Implement IP whitelist for sandbox API (office, VPN, CI/CD only)<br/>"
        "2. Use VPN or bastion host for sandbox access<br/>"
        "3. Separate sandbox from production infrastructure<br/>"
        "4. Add authentication layer for sandbox endpoints",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== MEDIUM SEVERITY ==========
    story.append(Paragraph("3. MEDIUM SEVERITY FINDINGS", heading1_style))
    
    # Finding 3.1
    story.append(Paragraph("3.1 No Rate Limiting Detected", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='#ff9900'>MEDIUM</font>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "Rapid sequential requests to both frontend and API endpoints show no rate limiting enforcement. "
        "Five consecutive requests completed without throttling (avg response time: 0.15s).",
        body_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Recommendations:</b>", body_style))
    story.append(Paragraph(
        "1. Implement rate limiting at Kong API Gateway<br/>"
        "2. Suggested limits: 100 req/min anonymous, 1000 req/min authenticated<br/>"
        "3. Add Cloudflare rate limiting rules",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    # Finding 3.2
    story.append(Paragraph("3.2 API Endpoints Leaked in JavaScript Bundle", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='#ff9900'>MEDIUM</font>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Exposed Endpoints:</b>", body_style))
    story.append(Paragraph(
        "<font face='Courier' size='8'>/v1/payments<br/>"
        "/v1/merchant/access<br/>"
        "/v1/merchant/payments/<br/>"
        "/v1/merchant/withdrawals<br/>"
        "/v1/merchant/withdrawals/info</font>",
        code_style
    ))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Recommendations:</b>", body_style))
    story.append(Paragraph(
        "1. Use runtime configuration instead of hardcoded paths<br/>"
        "2. Obfuscate API routes in production builds<br/>"
        "3. Implement dynamic endpoint discovery",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    # Finding 3.3
    story.append(Paragraph("3.3 Missing CORS Headers", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='#ff9900'>MEDIUM</font>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "No CORS (Cross-Origin Resource Sharing) headers observed on API responses, which could indicate "
        "either overly permissive or missing CORS configuration.",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    # Finding 3.4
    story.append(Paragraph("3.4 Cache-Control Misconfiguration", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='#ff9900'>MEDIUM</font>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    story.append(Paragraph("<b>Description:</b>", body_style))
    story.append(Paragraph(
        "Frontend serves all resources with <font face='Courier'>Cache-Control: public, max-age=0, must-revalidate</font>, "
        "which disables caching entirely and impacts performance.",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== LOW SEVERITY ==========
    story.append(Paragraph("4. LOW SEVERITY FINDINGS", heading1_style))
    
    story.append(Paragraph("4.1 Kong Gateway Version Disclosure", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='gray'>LOW</font>", body_style))
    story.append(Paragraph(
        "HTTP headers reveal Kong API Gateway usage via <font face='Courier'>x-kong-*</font> headers, "
        "providing technology stack information to attackers.",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("4.2 Webhook Endpoint Connectivity Issues", heading2_style))
    story.append(Paragraph("<b>Severity:</b> <font color='gray'>LOW</font>", body_style))
    story.append(Paragraph(
        "Affiliate webhook endpoint <font face='Courier'>gate.sumopod.com/webhook/sumopod/affiliate/verify</font> "
        "returns connection errors, indicating potential misconfiguration or downtime.",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== POSITIVE FINDINGS ==========
    story.append(Paragraph("5. POSITIVE SECURITY CONTROLS", heading1_style))
    
    story.append(Paragraph("<b>The following security measures were found to be properly implemented:</b>", body_style))
    story.append(Spacer(1, 0.3*cm))
    
    positive_findings = [
        "✅ Row Level Security (RLS) active on Supabase database",
        "✅ Cloudflare Web Application Firewall (WAF) blocks path traversal",
        "✅ HTTPS with HSTS enforced (max-age=31536000)",
        "✅ Content Security Policy (CSP) headers properly configured",
        "✅ X-Frame-Options: SAMEORIGIN prevents clickjacking",
        "✅ X-Content-Type-Options: nosniff prevents MIME sniffing",
        "✅ Cloudflare bot protection (Turnstile) active",
        "✅ Kong API Gateway properly rejects unauthorized routes"
    ]
    
    for finding in positive_findings:
        story.append(Paragraph(finding, body_style))
        story.append(Spacer(1, 0.2*cm))
    
    story.append(PageBreak())
    
    # ========== RECOMMENDATIONS ==========
    story.append(Paragraph("6. PRIORITIZED RECOMMENDATIONS", heading1_style))
    
    story.append(Paragraph("<b>IMMEDIATE (Within 24 hours):</b>", body_style))
    story.append(Paragraph(
        "1. Rotate Supabase anonymous key<br/>"
        "2. Sanitize error messages to remove hints<br/>"
        "3. IP-restrict sandbox payment API",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("<b>URGENT (Within 1 week):</b>", body_style))
    story.append(Paragraph(
        "4. Implement rate limiting at Kong and Cloudflare<br/>"
        "5. Audit all Supabase RLS policies<br/>"
        "6. Configure proper CORS headers<br/>"
        "7. Remove Kong version headers",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("<b>SHORT-TERM (Within 1 month):</b>", body_style))
    story.append(Paragraph(
        "8. Obfuscate API endpoints in JavaScript bundle<br/>"
        "9. Implement cache-control for static assets<br/>"
        "10. Set up automated security scanning (SAST/DAST)<br/>"
        "11. Conduct penetration testing by third party",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== METHODOLOGY ==========
    story.append(Paragraph("7. TESTING METHODOLOGY", heading1_style))
    
    story.append(Paragraph("<b>Reconnaissance:</b>", body_style))
    story.append(Paragraph(
        "• DNS and subdomain enumeration<br/>"
        "• HTTP header analysis<br/>"
        "• Technology stack fingerprinting<br/>"
        "• JavaScript bundle analysis",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("<b>Vulnerability Assessment:</b>", body_style))
    story.append(Paragraph(
        "• Authentication and authorization testing<br/>"
        "• API endpoint enumeration and fuzzing<br/>"
        "• Sensitive data exposure analysis<br/>"
        "• Error handling evaluation<br/>"
        "• Rate limiting tests",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("<b>Tools Used:</b>", body_style))
    story.append(Paragraph(
        "• curl (HTTP testing)<br/>"
        "• grep (pattern matching)<br/>"
        "• JWT decoder (token analysis)<br/>"
        "• Custom Python scripts",
        body_style
    ))
    
    story.append(PageBreak())
    
    # ========== DISCLAIMER ==========
    story.append(Paragraph("8. DISCLAIMER & SCOPE", heading1_style))
    
    story.append(Paragraph(
        "This security audit was conducted using publicly accessible information and non-invasive testing "
        "methods. No attempts were made to exploit discovered vulnerabilities or access unauthorized data. "
        "The scope was limited to external-facing endpoints and client-side resources.",
        body_style
    ))
    story.append(Spacer(1, 0.5*cm))
    
    story.append(Paragraph("<b>Out of Scope:</b>", body_style))
    story.append(Paragraph(
        "• Internal network penetration<br/>"
        "• Social engineering<br/>"
        "• Physical security<br/>"
        "• Authenticated user functionality<br/>"
        "• Mobile applications<br/>"
        "• Third-party integrations",
        body_style
    ))
    story.append(Spacer(1, 1*cm))
    
    # ========== SIGNATURE ==========
    story.append(Paragraph("<b>Report Prepared By:</b>", body_style))
    story.append(Spacer(1, 0.3*cm))
    story.append(Paragraph("Eko Budi", body_style))
    story.append(Paragraph("Security Analyst", body_style))
    story.append(Paragraph(f"{datetime.now().strftime('%d %B %Y')}", body_style))
    
    # Build PDF
    doc.build(story)
    print(f"✅ PDF report generated: {pdf_file}")
    return pdf_file

if __name__ == "__main__":
    create_security_report()
