"""
Bharat Tech Atlas — Security Utilities
Centralized security functions for input validation, output encoding,
audit logging, and threat detection.
v3.3: Unified security layer for all routes.
"""
import re
import hashlib
import hmac
import secrets
import time
import logging
from typing import Optional, List, Dict, Any
from urllib.parse import urlparse
from datetime import datetime
logger = logging.getLogger("bta.security")
# ─── Constants ────────────────────────────────────────────────────────────────
MAX_QUERY_STRING_LEN = 2048
MAX_PARAM_LEN = 512
MAX_BODY_SIZE = 1024 * 1024 # 1MB
MAX_CHAT_MSG_LEN = 4000
MAX_BATCH_SIZE = 50
ALLOWED_SCHEMES = {"http", "https"}
BLOCKED_HOSTS = {
"localhost", "127.0.0.1", "0.0.0.0", "::1",
"169.254.169.254", # AWS metadata
"192.168.", "10.", "172.16.", "172.17.", "172.18.", "172.19.",
"172.20.", "172.21.", "172.22.", "172.23.", "172.24.",
"172.25.", "172.26.", "172.27.", "172.28.", "172.29.",
"172.30.", "172.31.",
}
# Prompt injection patterns
PROMPT_INJECTION_PATTERNS = [
re.compile(r"ignore\s+previous\s+instructions", re.I),
re.compile(r"ignore\s+all\s+(?:prior|previous)\s+(?:instructions|rules)", re.I),
re.compile(r"system\s*:\s*you\s+are\s+now", re.I),
re.compile(r"new\s+system\s+prompt", re.I),
re.compile(r"\[/system\]", re.I),
re.compile(r"<\|system\|>", re.I),
re.compile(r"\[INST\]", re.I),
re.compile(r"\[/INST\]", re.I),
re.compile(r"\[SYSTEM\]", re.I),
re.compile(r"\[/SYSTEM\]", re.I),
re.compile(r"HUMAN:\s*", re.I),
re.compile(r"ASSISTANT:\s*", re.I),
re.compile(r"<>", re.I),
re.compile(r"<>", re.I),
re.compile(r"disregard\s+(?:the\s+)?(?:above|previous)", re.I),
re.compile(r"pretend\s+to\s*be", re.I),
re.compile(r"act\s+as\s+(?:if\s+)?you\s+are", re.I),
re.compile(r"you\s+are\s+now\s+(?:in\s+)?\s*(?:developer|debug|admin|root)\s*mode", re.I),
re.compile(r"DAN\s*\(?Do\s+Anything\s+Now\)?", re.I),
re.compile(r"jailbreak", re.I),
re.compile(r"ignore\s+your\s+(?:programming|training|guidelines)", re.I),
re.compile(r"bypass\s+(?:filters?|restrictions?|rules?)", re.I),
re.compile(r"\bDAN\b", re.I),
re.compile(r"\bSTAN\b", re.I),
re.compile(r"\bDUDE\b", re.I),
re.compile(r"\b Developer Mode \b", re.I),
re.compile(r"developer\s+mode\s*:\s*ON", re.I),
re.compile(r"\balways\b\s+\banswer\b\s+\band\b\s+\bnever\b", re.I),
]
# XSS patterns for output filtering
XSS_PATTERNS = [
re.compile(r"", re.I | re.S),
re.compile(r"javascript:", re.I),
re.compile(r"on\w+\s*=\s*['\"]?[^'\"]*['\"]?", re.I),
re.compile(r"